Module: Hanuman::TreeInstanceMethods
Constant Summary collapse
- MultipleRoots =
Class.new(TSort::Cyclic)
Instance Method Summary collapse
- #add_link(type, from, into) ⇒ Object
- #ancestor(stage) ⇒ Object
- #append(stage) ⇒ Object
- #directed_sort ⇒ Object
- #each_stage(&blk) ⇒ Object
- #leaves ⇒ Object
- #prepend(stage) ⇒ Object
- #root(stage = nil) ⇒ Object
- #tsort_each_child(label, &blk) ⇒ Object
- #tsort_each_node(&blk) ⇒ Object
Instance Method Details
#add_link(type, from, into) ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/hanuman/tree.rb', line 38 def add_link type, from, into return if has_link?(from, into) raise TSort::Cyclic.new("Cannot link from a stage <#{from.label}> to itself") if into == from raise MultipleRoots.new("Cannot link from <#{from.label}> to <#{into.label}> because <#{into.label}> aleady has an ancestor <#{ancestor(into).label}>") if ancestor(into) raise TSort::Cyclic.new("Cannot link from leaf <#{from.label}> to the root <#{into.label}>") if into == root && leaves.include?(from) super(type, from, into) end |
#ancestor(stage) ⇒ Object
29 30 31 |
# File 'lib/hanuman/tree.rb', line 29 def ancestor(stage) ancestors(stage).first end |
#append(stage) ⇒ Object
50 51 52 53 54 55 56 |
# File 'lib/hanuman/tree.rb', line 50 def append stage leaves.each do |leaf| stage_for_leaf = stage.clone stage_for_leaf.label = "#{stage_for_leaf.label}_for_#{leaf.label}".to_sym add_link(:simple, leaf, stage_for_leaf) end end |
#directed_sort ⇒ Object
17 |
# File 'lib/hanuman/tree.rb', line 17 def directed_sort() self.tsort ; end |
#each_stage(&blk) ⇒ Object
19 20 21 |
# File 'lib/hanuman/tree.rb', line 19 def each_stage &blk directed_sort.map { |label| stages[label]}.compact.each(&blk) end |
#leaves ⇒ Object
33 34 35 36 |
# File 'lib/hanuman/tree.rb', line 33 def leaves the_leaves = (descendents - ancestors) the_leaves.empty? ? [root] : the_leaves end |
#prepend(stage) ⇒ Object
46 47 48 |
# File 'lib/hanuman/tree.rb', line 46 def prepend stage add_link(:simple, stage, root) end |
#root(stage = nil) ⇒ Object
23 24 25 26 27 |
# File 'lib/hanuman/tree.rb', line 23 def root stage=nil return stages[directed_sort.first] unless stage return stage unless ancestor(stage) self.root(ancestor(stage)) end |
#tsort_each_child(label, &blk) ⇒ Object
13 14 15 |
# File 'lib/hanuman/tree.rb', line 13 def tsort_each_child(label, &blk) links.select { |link| link.into == label }.map(&:from).each(&blk) end |
#tsort_each_node(&blk) ⇒ Object
9 10 11 |
# File 'lib/hanuman/tree.rb', line 9 def tsort_each_node(&blk) stages.keys.each(&blk) end |