Class: Nutella::PersistedHash

Inherits:
Object
  • Object
show all
Defined in:
lib/config/persisted_hash.rb

Overview

This class behaves similarly to a regular Hash but it persists every operation to the json file passed in the constructor. Not all Hash operations are supported and we added some of our own.

Direct Known Subclasses

RunListHash

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ PersistedHash

Returns a new instance of PersistedHash.



10
11
12
# File 'lib/config/persisted_hash.rb', line 10

def initialize(file)
  @config_file=file
end

Instance Method Details

#[](key) ⇒ Object



14
15
16
17
# File 'lib/config/persisted_hash.rb', line 14

def []( key )
  hash = load_hash
  hash[key]
end

#[]=(key, val) ⇒ Object



19
20
21
22
23
# File 'lib/config/persisted_hash.rb', line 19

def []=( key, val )
  hash = load_hash
  hash[key]=val
  store_hash hash
end

#add?(key, val) ⇒ Boolean

Adds a <key, value> pair to the PersistedHash _only if_ there is currently no value associated with the specified key. <key, value> pair was added successfully

Returns:

  • (Boolean)

    false if the key already exists, true if the



71
72
73
74
75
76
77
# File 'lib/config/persisted_hash.rb', line 71

def add?(key, val)
  hash = load_hash
  return false if hash.key? key
  hash[key] = val
  store_hash hash
  true
end

#delete(key) ⇒ Object



25
26
27
28
29
30
# File 'lib/config/persisted_hash.rb', line 25

def delete( key )
  hash = load_hash
  return_value = hash.delete key
  store_hash hash
  return_value
end

#delete?(key) ⇒ Boolean

Removes a <key, value> pair from the PersistedHash _only if_ there is currently a value associated with the specified key. the specified key, true otherwise

Returns:

  • (Boolean)

    false if there is no value associated with



83
84
85
86
87
88
# File 'lib/config/persisted_hash.rb', line 83

def delete?( key )
  hash = load_hash
  return false if hash.delete(key).nil?
  store_hash hash
  true
end

#empty?Boolean

Returns:

  • (Boolean)


32
33
34
35
# File 'lib/config/persisted_hash.rb', line 32

def empty?
  hash = load_hash
  hash.empty?
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
# File 'lib/config/persisted_hash.rb', line 37

def has_key?( key )
  hash = load_hash
  hash.has_key? key
end

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/config/persisted_hash.rb', line 42

def include?( key )
  has_key? key
end

#keysObject



55
56
57
58
# File 'lib/config/persisted_hash.rb', line 55

def keys
  hash = load_hash
  hash.keys
end

#lengthObject



60
61
62
63
# File 'lib/config/persisted_hash.rb', line 60

def length
  hash = load_hash
  hash.length
end

#to_hObject



51
52
53
# File 'lib/config/persisted_hash.rb', line 51

def to_h
  load_hash
end

#to_sObject



46
47
48
49
# File 'lib/config/persisted_hash.rb', line 46

def to_s
  hash = load_hash
  hash.to_s
end