Class: KeyValueTree::Hash
- Inherits:
-
Object
- Object
- KeyValueTree::Hash
show all
- Defined in:
- lib/keyvaluetree/hash.rb
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(store = KeyValueTree::MemoryStore.new(), key = nil, parent = nil) ⇒ Hash
Returns a new instance of Hash.
7
8
9
10
11
|
# File 'lib/keyvaluetree/hash.rb', line 7
def initialize(store = KeyValueTree::MemoryStore.new(), key=nil, parent = nil)
@key = key.to_s
@parent = parent
@store = store
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args) ⇒ Object
37
38
39
40
41
42
43
44
|
# File 'lib/keyvaluetree/hash.rb', line 37
def method_missing(method, *args)
property = method.to_s
if property =~ /=$/
return self[property.chop] = args[0]
else
return self[property]
end
end
|
Instance Attribute Details
#store ⇒ Object
Returns the value of attribute store.
5
6
7
|
# File 'lib/keyvaluetree/hash.rb', line 5
def store
@store
end
|
Instance Method Details
#[](key) ⇒ Object
13
14
15
16
17
18
|
# File 'lib/keyvaluetree/hash.rb', line 13
def [] (key)
return self if key.nil?
value = @store.key(key_path_string(key))
return value unless value.nil?
return KeyValueTree::Hash.new(@store, key, self)
end
|
#[]=(key, value) ⇒ Object
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# File 'lib/keyvaluetree/hash.rb', line 20
def []= (key, value)
if value.is_a?(::Hash)
value.each do |hash_key, hash_value|
self[key][hash_key] = hash_value
end
return
end
@store.store(key_path_string(key), value)
return value
end
|
#delete(key) ⇒ Object
73
74
75
|
# File 'lib/keyvaluetree/hash.rb', line 73
def delete(key)
@store.delete(key_path_string(key.to_s))
end
|
#import(object) ⇒ Object
81
82
83
|
# File 'lib/keyvaluetree/hash.rb', line 81
def import(object)
self[nil] = object
end
|
#key_path(key = nil) ⇒ Object
46
47
48
49
50
51
52
53
54
|
# File 'lib/keyvaluetree/hash.rb', line 46
def key_path(key = nil)
if root?
return [] if key.nil?
return [key.to_s]
else
return (@parent.key_path + [@key]).compact if key.nil?
return (@parent.key_path + [@key, key.to_s]).compact
end
end
|
#key_path_string(key = nil) ⇒ Object
56
57
58
59
60
61
62
63
64
65
66
67
|
# File 'lib/keyvaluetree/hash.rb', line 56
def key_path_string(key = nil)
result = ''
key_path(key).each_with_index do |value, index|
result = result + '.' unless index == 0
result = result + value
end
return result
end
|
#keys ⇒ Object
77
78
79
|
# File 'lib/keyvaluetree/hash.rb', line 77
def keys
@store.keys_starting_with(key_path_string()).map { |each| each.split(".").first }.uniq
end
|
#root? ⇒ Boolean
69
70
71
|
# File 'lib/keyvaluetree/hash.rb', line 69
def root?
@parent.nil?
end
|