Class: Iriq::Storage::Json

Inherits:
Memory
  • Object
show all
Defined in:
lib/iriq/storage/json.rb

Overview

Json wraps Memory with load-from-file at open and save-to-file at close. Same JSON shape as the pre-Storage release, so files round-trip across versions.

Instance Attribute Summary collapse

Attributes inherited from Memory

#max_values_per_position

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Memory

#add_to_cluster, #batch, #close, #cluster_size, #clusters, #each_position_stats, #fingerprint_counts, #flush, #host_counts, #increment_fingerprint, #increment_host, #increment_path_length, #increment_raw_shape, #load_dump!, #observe_position, #path_length_counts, #position_stats, #raw_shape_counts, #to_dump, #transaction

Constructor Details

#initialize(path: nil, **opts) ⇒ Json

Returns a new instance of Json.



11
12
13
14
# File 'lib/iriq/storage/json.rb', line 11

def initialize(path: nil, **opts)
  super(**opts)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/iriq/storage/json.rb', line 9

def path
  @path
end

Class Method Details

.open(path, **opts) ⇒ Object



16
17
18
19
20
# File 'lib/iriq/storage/json.rb', line 16

def self.open(path, **opts)
  s = new(path: path, **opts)
  s.load!(path) if File.exist?(path) && File.size(path).positive?
  s
end

Instance Method Details

#load!(path) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/iriq/storage/json.rb', line 22

def load!(path)
  data = File.read(path)
  return self if data.empty?

  load_dump!(JSON.parse(data))
  @path = path
  self
end

#save(path = nil) ⇒ Object

save writes atomically (tmp + rename). Defaults to the path passed at open(); pass an explicit path to write elsewhere.

Raises:

  • (ArgumentError)


33
34
35
36
37
38
39
40
# File 'lib/iriq/storage/json.rb', line 33

def save(path = nil)
  target = path || @path
  raise ArgumentError, "no path provided" unless target

  tmp = "#{target}.tmp"
  File.write(tmp, JSON.generate(to_dump))
  File.rename(tmp, target)
end