Class: ObjectGraphTraverser

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

Instance Method Summary collapse

Constructor Details

#initialize(object_graph) ⇒ ObjectGraphTraverser

Params:

object_graph

a hash of class name => association pairs, e.g.

{ 'Foo' => ['bars'], 'Bar' => ['baz'] }


6
7
8
# File 'lib/object_graph_traverser.rb', line 6

def initialize(object_graph)
  @graph = object_graph
end

Instance Method Details

#traverse_graph(object, parent = nil, &block) ⇒ Object

Given a starting object, traverses the graph calling the given block on each node.

Params:

object

root object from which to start traversing

parent

optional parent object

block

a block that will be called on each node, receiving the node, its parent and the graph of objects under the current node.



16
17
18
19
20
21
22
23
24
# File 'lib/object_graph_traverser.rb', line 16

def traverse_graph(object,parent=nil,&block)
  nodes = fetch_object_graph(object.class).map do |node|
    Array(object.send(node.to_sym)).each do |node_object|
      traverse_graph(node_object,object,&block)
    end
    node
  end
  block.call(object,parent,nodes)
end