Class: Legion::Data::Spool::ScopedSpool

Inherits:
Object
  • Object
show all
Defined in:
lib/legion/data/spool.rb

Instance Method Summary collapse

Constructor Details

#initialize(extension_module, spool_root) ⇒ ScopedSpool

Returns a new instance of ScopedSpool.



34
35
36
# File 'lib/legion/data/spool.rb', line 34

def initialize(extension_module, spool_root)
  @extension_dir = File.join(spool_root, Spool.send(:extension_path, extension_module))
end

Instance Method Details

#clear(sub_namespace) ⇒ Object



68
69
70
71
72
73
# File 'lib/legion/data/spool.rb', line 68

def clear(sub_namespace)
  dir = sub_dir(sub_namespace)
  return unless Dir.exist?(dir)

  Dir[File.join(dir, '*.json')].each { |f| File.delete(f) }
end

#count(sub_namespace) ⇒ Object



64
65
66
# File 'lib/legion/data/spool.rb', line 64

def count(sub_namespace)
  sorted_files(sub_namespace).size
end

#flush(sub_namespace) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/legion/data/spool.rb', line 52

def flush(sub_namespace)
  count = 0
  sorted_files(sub_namespace).each do |path|
    event = ::JSON.parse(File.read(path), symbolize_names: true)
    yield event
    File.delete(path)
    count += 1
  end
  Legion::Logging.info "Spool drained #{count} item(s) from #{sub_namespace}" if defined?(Legion::Logging) && count.positive?
  count
end

#read(sub_namespace) ⇒ Object



48
49
50
# File 'lib/legion/data/spool.rb', line 48

def read(sub_namespace)
  sorted_files(sub_namespace).map { |f| ::JSON.parse(File.read(f), symbolize_names: true) }
end

#write(sub_namespace, payload) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/legion/data/spool.rb', line 38

def write(sub_namespace, payload)
  dir = sub_dir(sub_namespace)
  FileUtils.mkdir_p(dir)
  filename = "#{Time.now.strftime('%s%9N')}-#{SecureRandom.uuid}.json"
  path = File.join(dir, filename)
  File.write(path, ::JSON.generate(payload))
  Legion::Logging.debug "Spool write: #{sub_namespace} -> #{filename}" if defined?(Legion::Logging)
  path
end