Class: KeyValueTree::Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/keyvaluetree/hash.rb

Instance Method Summary collapse

Constructor Details

#initialize(store = KeyValueTree::MemoryStore.new(), key = nil, parent = nil) ⇒ Hash

Returns a new instance of Hash.



5
6
7
8
9
# File 'lib/keyvaluetree/hash.rb', line 5

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



34
35
36
37
38
39
40
41
# File 'lib/keyvaluetree/hash.rb', line 34

def method_missing(method, *args)
  property = method.to_s
  if property =~ /=$/
    return self[property.chop] = args[0]
  else
    return self[property]
  end
end

Instance Method Details

#[](key) ⇒ Object



11
12
13
14
15
# File 'lib/keyvaluetree/hash.rb', line 11

def [] (key)
  value = @store.key(key_path_string(key))
  return value unless value.nil?
  return KeyValueTree::Hash.new(@store, key, self)
end

#[]=(key, value) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/keyvaluetree/hash.rb', line 17

def []= (key, value)
  if value.is_a?(Hash)
    value.each do |hash_key, hash_value|
      self[key_path_string(key)][hash_key] = hash_value
    end
    return
  end
  #if value.is_a?(Array)
  #  value.each_with_index do |value, index|
  #    self[key][index] = value
  #  end
  #  return
  #end
  @store.store(key_path_string(key), value)
  return value
end

#delete(key) ⇒ Object



70
71
72
# File 'lib/keyvaluetree/hash.rb', line 70

def delete(key)
  @store.delete(key_path_string(key.to_s))
end

#key_path(key = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/keyvaluetree/hash.rb', line 43

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



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/keyvaluetree/hash.rb', line 53

def key_path_string(key = nil)
  result = ''
  key_path(key).each_with_index do |value, index|
    # if value.is_a?(Integer)
    #  result = result + "[#{value}]"
    # else
    result = result + '.' unless index == 0
    result = result + value
    # end
  end
  return result
end

#keysObject



74
75
76
# File 'lib/keyvaluetree/hash.rb', line 74

def keys
  @store.keys_starting_with(key_path_string()).map { |each| each.split(".").first }.uniq
end

#root?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/keyvaluetree/hash.rb', line 66

def root?
  @parent.nil?
end