/
node_traverser.rb
69 lines (55 loc) · 1.7 KB
/
node_traverser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
module Neo4j
module Relations
# Enables traversing nodes
# TODO duplicated code, see RelationTraverser, Inheritance ?
class NodeTraverser
include Enumerable
attr_reader :internal_node
def initialize(internal_node)
@internal_node = internal_node
@direction = org.neo4j.api.core.Direction::BOTH
@stop_evaluator = DepthStopEvaluator.new(1)
end
def outgoing(type = nil)
@type = type
@direction = org.neo4j.api.core.Direction::OUTGOING
self
end
def incoming(type = nil)
@type = type
@direction = org.neo4j.api.core.Direction::INCOMING
self
end
def both(type = nil)
@type = type
@direction = org.neo4j.api.core.Direction::BOTH
self
end
def empty?
Neo4j::Transaction.run {!iterator.hasNext}
end
def each
Neo4j::Transaction.run do
iter = iterator
while (iter.hasNext) do
n = iter.next
yield Neo4j.load(n.get_id)
end
end
end
def iterator
# check that we know which type of relationship should be traversed
raise "Unknown type of relationship. Need to know which type(s) of relationship in order to traverse" if @type.nil?
# create the traverser iterator
@internal_node.traverse(org.neo4j.api.core.Traverser::Order::BREADTH_FIRST,
@stop_evaluator,
org.neo4j.api.core.ReturnableEvaluator::ALL_BUT_START_NODE,
RelationshipType.instance(@type),
@direction).iterator
end
def to_s
"NodeTraverser [direction=#{@direction}, type=#{@type}]"
end
end
end
end