Class: GraphQL::Language::Visitor

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/language/visitor.rb

Overview

Depth-first traversal through the tree, calling hooks at each stop.

Examples:

Create a visitor, add hooks, then search a document

total_field_count = 0
visitor = GraphQL::Language::Visitor.new
# Whenever you find a field, increment the field count:
visitor[GraphQL::Language::Nodes::Field] << -> (node) { total_field_count += 1 }
# When we finish, print the field count:
visitor[GraphQL::Language::Nodes::Document].leave << -> (node) { p total_field_count }
visitor.visit(document)
# => 6

Defined Under Namespace

Classes: NodeVisitor

Constant Summary collapse

SKIP =

If any hook returns this value, the GraphQL::Language::Visitor stops visiting this node right away

:_skip

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeVisitor

Returns a new instance of Visitor.



23
24
25
26
27
# File 'lib/graphql/language/visitor.rb', line 23

def initialize
  @visitors = {}
  @enter = []
  @leave = []
end

Instance Attribute Details

#enterArray<Proc> (readonly)

Returns Hooks to call when entering any node.

Returns:

  • (Array<Proc>)

    Hooks to call when entering any node



19
20
21
# File 'lib/graphql/language/visitor.rb', line 19

def enter
  @enter
end

#leaveArray<Proc> (readonly)

Returns Hooks to call when leaving any node.

Returns:

  • (Array<Proc>)

    Hooks to call when leaving any node



21
22
23
# File 'lib/graphql/language/visitor.rb', line 21

def leave
  @leave
end

Instance Method Details

#[](node_class) ⇒ NodeVisitor

Get a NodeVisitor for ‘node_class`

Examples:

Run a hook whenever you enter a new Field

visitor[GraphQL::Language::Nodes::Field] << -> (node, parent) { p "Here's a field" }

Parameters:

  • node_class (Class)

    The node class that you want to listen to

Returns:



35
36
37
# File 'lib/graphql/language/visitor.rb', line 35

def [](node_class)
  @visitors[node_class] ||= NodeVisitor.new
end

#visit(root, parent = nil) ⇒ void

This method returns an undefined value.

Visit ‘root` and all children, applying hooks as you go

Parameters:



42
43
44
45
46
# File 'lib/graphql/language/visitor.rb', line 42

def visit(root, parent=nil)
  begin_visit(root, parent) &&
    root.children.reduce(true) { |memo, child| memo && visit(child, root) }
  end_visit(root, parent)
end