Class: Modern::Util::TrieNode

Inherits:
Object
  • Object
show all
Defined in:
lib/modern/util/trie_node.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = []) ⇒ TrieNode

Returns a new instance of TrieNode.



14
15
16
17
# File 'lib/modern/util/trie_node.rb', line 14

def initialize(path = [])
  @path = path
  @children = {}
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



12
13
14
# File 'lib/modern/util/trie_node.rb', line 12

def children
  @children
end

#parentObject (readonly)

Returns the value of attribute parent.



8
9
10
# File 'lib/modern/util/trie_node.rb', line 8

def parent
  @parent
end

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/modern/util/trie_node.rb', line 9

def path
  @path
end

#valueObject

Returns the value of attribute value.



10
11
12
# File 'lib/modern/util/trie_node.rb', line 10

def value
  @value
end

Instance Method Details

#[](child_name) ⇒ Object



37
38
39
# File 'lib/modern/util/trie_node.rb', line 37

def [](child_name)
  @children[child_name] || @children[:templated]
end

#add(key, value, raise_if_present: false) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/modern/util/trie_node.rb', line 19

def add(key, value, raise_if_present: false)
  key = [key].flatten

  if key.empty?
    if @value
      raise Modern::Errors::RoutingError, "Existing value at #{path.inspect}: #{@value}" \
        if raise_if_present
    end

    @value = value
  else
    child_name = key.first
    @children[child_name] ||= TrieNode.new(path + [child_name])

    @children[child_name].add(key[1..-1], value, raise_if_present: raise_if_present)
  end
end

#get(key = []) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/modern/util/trie_node.rb', line 41

def get(key = [])
  key = [key].flatten

  node = self
  until key.empty? || node.nil?
    node = node[key.shift]
  end

  node&.value
end