Class: Tequila::Tree

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTree

Returns a new instance of Tree.



44
45
46
47
48
# File 'lib/tree.rb', line 44

def initialize
  @root = OpenStruct.new({:name => :root})
  @tree = { @root => [] }
  @config = Tequila::Config.new
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



42
43
44
# File 'lib/tree.rb', line 42

def config
  @config
end

#rootObject (readonly)

Returns the value of attribute root.



41
42
43
# File 'lib/tree.rb', line 41

def root
  @root
end

Instance Method Details

#add_child_to(branch, child) ⇒ Object



50
51
52
53
# File 'lib/tree.rb', line 50

def add_child_to(branch, child)
  @tree[branch] ||= []
  @tree[branch] << child
end

#build_hashObject



63
64
65
66
67
68
69
# File 'lib/tree.rb', line 63

def build_hash
  res = @tree[root].inject({}) do |out, n|
    out.merge(build_hash_with_context(n, n.content.call))
  end
  ((res.values.first.kind_of? Array) && !config.show_initial_label) ?
  res.values.first : res
end

#build_hash_with_context(node, context) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/tree.rb', line 71

def build_hash_with_context(node, context)
  if context.kind_of? Array
    { node.label =>
      context.map do |elementary_context|
        build_hash_with_context(node, elementary_context)
      end
    }
  elsif @tree[node]
    node_value = node.apply(context).merge(
      @tree[node].inject({}) do |out, n|
        new_context = n.content.call(context)
        if new_context.nil?
          out
        else
          if n.bounded?
            out.merge(build_hash_with_context(n, new_context).values.first)
          else
            out.merge(build_hash_with_context(n, new_context))
          end
        end
      end)
    node.suppress_label ?
      node_value :
      { node.label.singularize => node_value }
  else
    node.suppress_label ?
      node.apply(context) :
      { node.label.singularize => node.apply(context) }
  end
end

#nodesObject



59
60
61
# File 'lib/tree.rb', line 59

def nodes
  @tree.values.inject([]){ |res, nodes| res + nodes }.uniq
end

#parent_for?(node) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/tree.rb', line 55

def parent_for?(node)
  @tree.keys.select {|n| @tree[n].include?(node)}[0]
end

#to_sObject



102
103
104
105
106
107
108
109
# File 'lib/tree.rb', line 102

def to_s
  nodes.inject('') do |res, node|
    res <<
    node.to_s  <<
    (node.bounded? ? " bounded_to: " : " parent: ") <<
    "#{parent_for?(node).name}\n"
  end
end