Class: NodeQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/node_query.rb,
lib/node_query/version.rb

Defined Under Namespace

Modules: Compiler Classes: Adapter, Helper, InvalidAdapterError, MethodNotSupported, NodeRules, ParserAdapter, PrismAdapter, SyntaxTreeAdapter

Constant Summary collapse

VERSION =
"1.16.0"

Instance Method Summary collapse

Constructor Details

#initialize(nql_or_ruls, adapter: :parser) ⇒ NodeQuery

Initialize a NodeQuery.

Parameters:

  • nql_or_ruls (String | Hash)

    node query language or node rules

  • adapter (Symbol) (defaults to: :parser)

    :parser or :syntax_tree



22
23
24
25
26
27
28
29
# File 'lib/node_query.rb', line 22

def initialize(nql_or_ruls, adapter: :parser)
  adapter_instance = get_adapter_instance(adapter)
  if nql_or_ruls.is_a?(String)
    @expression = NodeQueryParser.new(adapter: adapter_instance).parse(nql_or_ruls)
  else
    @rules = NodeRules.new(nql_or_ruls, adapter: adapter_instance)
  end
end

Instance Method Details

#match_node?(node) ⇒ Boolean

Check if the node matches the nql or rules.

Parameters:

  • node (Node)

    the node

Returns:

  • (Boolean)


51
52
53
54
55
56
57
58
59
# File 'lib/node_query.rb', line 51

def match_node?(node)
  if @expression
    @expression.match_node?(node)
  elsif @rules
    @rules.match_node?(node)
  else
    false
  end
end

#query_nodes(node, options = {}) ⇒ Array<Node>

Query matching nodes.

Parameters:

  • node (Node)

    ast node

  • options (Hash) (defaults to: {})

    if query the current node

Options Hash (options):

  • :including_self (boolean)

    if query the current node, default is ture

  • :stop_at_first_match (boolean)

    if stop at first match, default is false

  • :recursive (boolean)

    if recursively query child nodes, default is true

Returns:

  • (Array<Node>)

    matching child nodes



38
39
40
41
42
43
44
45
46
# File 'lib/node_query.rb', line 38

def query_nodes(node, options = {})
  if @expression
    @expression.query_nodes(node, options)
  elsif @rules
    @rules.query_nodes(node, options)
  else
    []
  end
end