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 Method Summary collapse

Constructor Details

#initialize(document) ⇒ Visitor

Returns a new instance of Visitor.



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

def initialize(document)
  @document = document
  @visitors = {}
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:



32
33
34
# File 'lib/graphql/language/visitor.rb', line 32

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



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

def visit
  visit_node(@document, nil)
end