Class: Fractor::QueuePersister::JSONPersister

Inherits:
Base
  • Object
show all
Defined in:
lib/fractor/queue_persister.rb

Overview

JSON file persister. Stores queue state as a JSON array.

Instance Method Summary collapse

Constructor Details

#initialize(path, pretty: true) ⇒ JSONPersister

Initialize a JSON persister.

Parameters:

  • path (String)

    Path to the JSON file

  • pretty (Boolean) (defaults to: true)

    Format JSON with indentation



65
66
67
68
# File 'lib/fractor/queue_persister.rb', line 65

def initialize(path, pretty: true)
  @path = path
  @pretty = pretty
end

Instance Method Details

#clearBoolean

Clear the JSON file.

Returns:

  • (Boolean)

    true if cleared successfully



105
106
107
108
109
110
111
# File 'lib/fractor/queue_persister.rb', line 105

def clear
  File.delete(@path) if File.exist?(@path)
  true
rescue StandardError => e
  warn "Failed to clear #{@path}: #{e.message}"
  false
end

#loadArray<Hash>?

Load work items from JSON file.

Returns:

  • (Array<Hash>, nil)

    Serialized work items, or nil if file doesn't exist



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/fractor/queue_persister.rb', line 90

def load
  return nil unless File.exist?(@path)

  json = File.read(@path)
  return nil if json.strip.empty?

  JSON.parse(json)
rescue StandardError => e
  warn "Failed to load from #{@path}: #{e.message}"
  nil
end

#save(items) ⇒ Boolean

Save work items to JSON file.

Parameters:

Returns:

  • (Boolean)

    true if saved successfully



74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/fractor/queue_persister.rb', line 74

def save(items)
  ensure_directory_exists

  serialized = items.map { |work| serialize_work(work) }
  json = @pretty ? JSON.pretty_generate(serialized) : JSON.generate(serialized)

  File.write(@path, json)
  true
rescue StandardError => e
  warn "Failed to save to #{@path}: #{e.message}"
  false
end