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(document)
# 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
# => 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

#initialize(document) ⇒ Visitor

Returns a new instance of Visitor.



25
26
27
28
29
30
# File 'lib/graphql/language/visitor.rb', line 25

def initialize(document)
  @document = document
  @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



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

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



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

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:



38
39
40
# File 'lib/graphql/language/visitor.rb', line 38

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

#visitvoid

This method returns an undefined value.

Visit document and all children, applying hooks as you go



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

def visit
  visit_node(@document, nil)
end