class JSONFilePersistedHash
An hash that is automatically persisted to a JSON file. This class behaves similarly to a regular Hash but it persists every operation to a specified JSON file. Not all Hash operations are supported and we added some of our own.
Public Class Methods
new( file )
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 9 def initialize( file ) @store = JSONStore.new(file, true) end
Public Instance Methods
[]( key )
click to toggle source
Methods borrowed from Ruby's Hash class
# File lib/util/json_file_persisted_hash.rb, line 16 def []( key ) @store.transaction { @store[key] } end
[]=( key, val )
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 20 def []=( key, val ) @store.transaction { @store[key]=val } end
add_key_value?(key, val)
click to toggle source
Adds a <key, value> pair to the PersistedHash _only if_ there is currently no value associated with the specified key. @return [Boolean] false if the key already exists, true if the <key, value> pair was added successfully
# File lib/util/json_file_persisted_hash.rb, line 67 def add_key_value?(key, val) @store.transaction do return false if @store.to_h.key? key @store[key]=val end true end
delete( key )
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 24 def delete( key ) @store.transaction { @store.delete key } end
delete_key_value?( key )
click to toggle source
Removes a <key, value> pair from the PersistedHash _only if_ there is currently a value associated with the specified key. @return [Boolean] false if there is no value associated with the specified key, true otherwise
# File lib/util/json_file_persisted_hash.rb, line 79 def delete_key_value?( key ) @store.transaction { return false if @store.delete(key).nil? } true end
empty?()
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 28 def empty? @store.transaction { @store.to_h.empty? } end
has_key?( key )
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 32 def has_key?( key ) @store.transaction { @store.to_h.has_key? key } end
include?( key )
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 36 def include?( key ) has_key? key end
keys()
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 48 def keys @store.transaction { @store.to_h.keys } end
length()
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 52 def length @store.transaction { @store.to_h.length } end
merge!( other_hash )
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 56 def merge!( other_hash ) @store.transaction { other_hash.each { |k, v| @store[k] = v } } end
to_h()
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 44 def to_h @store.transaction { @store.to_h } end
to_s()
click to toggle source
# File lib/util/json_file_persisted_hash.rb, line 40 def to_s @store.transaction { @store.to_h.to_s } end