Class: KeyTree::Tree
- Inherits:
-
Hash
- Object
- Hash
- KeyTree::Tree
show all
- Includes:
- MetaData
- Defined in:
- lib/key_tree/tree.rb
Overview
A tree of key-value lookup tables (hashes)
Class Method Summary
collapse
Instance Method Summary
collapse
Methods included from MetaData
#meta_data, #with_meta_data
Class Method Details
.[](hash = {}) ⇒ Object
KeyTree::Tree.new(hash)
Initialize a new KeyTree from nested Hash:es
12
13
14
15
16
17
18
|
# File 'lib/key_tree/tree.rb', line 12
def self.[](hash = {})
keytree = Tree.new
hash.each do |key, value|
keytree[key] = value
end
keytree
end
|
Instance Method Details
#<=>(other) ⇒ Object
All trees are created equal. Forests are always larger than trees.
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/key_tree/tree.rb', line 59
def <=>(other)
case other
when Forest
-1
when Tree
0
else
raise ArgumentError, 'only trees and forests are comparable'
end
end
|
#[](key_or_path) ⇒ Object
20
21
22
|
# File 'lib/key_tree/tree.rb', line 20
def [](key_or_path)
super(Path[key_or_path])
end
|
#[]=(key_or_path, new_value) ⇒ Object
32
33
34
35
36
37
38
39
40
41
42
43
|
# File 'lib/key_tree/tree.rb', line 32
def []=(key_or_path, new_value)
path = Path[key_or_path]
delete_if { |key, _| path.conflict?(key) }
case new_value
when Hash
new_value.each { |suffix, value| super(path + suffix, value) }
else
super(path, new_value)
end
end
|
#conflict?(key_or_path) ⇒ Boolean
53
54
55
|
# File 'lib/key_tree/tree.rb', line 53
def conflict?(key_or_path)
keys.any? { |key| key.conflict?(Path[key_or_path]) }
end
|
#fetch(key_or_path, *args, &proc) ⇒ Object
24
25
26
|
# File 'lib/key_tree/tree.rb', line 24
def fetch(key_or_path, *args, &proc)
super(Path[key_or_path], *args, &proc)
end
|
#key?(key_or_path) ⇒ Boolean
45
46
47
|
# File 'lib/key_tree/tree.rb', line 45
def key?(key_or_path)
super(Path[key_or_path])
end
|
#merge(other) ⇒ Object
Also known as:
+
80
81
82
|
# File 'lib/key_tree/tree.rb', line 80
def merge(other)
dup.merge!(other)
end
|
#merge!(other) ⇒ Object
Also known as:
<<
The merging of trees needs some extra consideration; due to the nature of key paths, prefix conflicts must be deleted
73
74
75
76
77
|
# File 'lib/key_tree/tree.rb', line 73
def merge!(other)
other = Tree[other] unless other.is_a?(Tree)
delete_if { |key, _| other.conflict?(key) }
super
end
|
#prefix?(key_or_path) ⇒ Boolean
49
50
51
|
# File 'lib/key_tree/tree.rb', line 49
def prefix?(key_or_path)
keys.any? { |key| key.prefix?(Path[key_or_path]) }
end
|
#values_at(*keys) ⇒ Object
28
29
30
|
# File 'lib/key_tree/tree.rb', line 28
def values_at(*keys)
super(keys.map { |key_or_path| Path[key_or_path] })
end
|