Class: UtilityPack::PersistentHash

Inherits:
Object
  • Object
show all
Defined in:
lib/utility_pack/persistenthash.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ PersistentHash

Returns a new instance of PersistentHash.



8
9
10
# File 'lib/utility_pack/persistenthash.rb', line 8

def initialize path
  @path = path
end

Instance Method Details

#[](key) ⇒ Object



24
25
26
# File 'lib/utility_pack/persistenthash.rb', line 24

def [](key)
   load[key]
end

#[]=(key, value) ⇒ Object



28
29
30
31
32
# File 'lib/utility_pack/persistenthash.rb', line 28

def []=(key, value)
  h = load
  h[key] = value
  save(h)
end

#json_parse_file(path) ⇒ Object



12
13
14
# File 'lib/utility_pack/persistenthash.rb', line 12

def json_parse_file(path)
  JSON.parse(File.read_file(path))
end

#loadObject



16
17
18
# File 'lib/utility_pack/persistenthash.rb', line 16

def load
  ::File.exists?(@path) ? json_parse_file(@path) : {}
end

#save(h) ⇒ Object



20
21
22
# File 'lib/utility_pack/persistenthash.rb', line 20

def save h
  ::File.write_file @path, h.to_json
end