Class: Synvert::Core::NodeQuery::Compiler::Selector

Inherits:
Object
  • Object
show all
Defined in:
lib/synvert/core/node_query/compiler/selector.rb

Overview

Selector used to match nodes, it combines by node type and/or attribute list, plus index or has expression.

Instance Method Summary collapse

Constructor Details

#initialize(goto_scope: nil, relationship: nil, rest: nil, basic_selector: nil, pseudo_class: nil, pseudo_selector: nil) ⇒ Selector

Initialize a Selector.

Parameters:



14
15
16
17
18
19
20
21
# File 'lib/synvert/core/node_query/compiler/selector.rb', line 14

def initialize(goto_scope: nil, relationship: nil, rest: nil, basic_selector: nil, pseudo_class: nil, pseudo_selector: nil)
  @goto_scope = goto_scope
  @relationship = relationship
  @rest = rest
  @basic_selector = basic_selector
  @pseudo_class = pseudo_class
  @pseudo_selector = pseudo_selector
end

Instance Method Details

#match?(node) ⇒ Boolean

Check if node matches the selector.

Parameters:

Returns:



25
26
27
# File 'lib/synvert/core/node_query/compiler/selector.rb', line 25

def match?(node)
  node.is_a?(::Parser::AST::Node) && (!@basic_selector || @basic_selector.match?(node)) && match_pseudo_class?(node)
end

#query_nodes(node) ⇒ Array<Parser::AST::Node>

Query nodes by the selector.

  • If relationship is nil, it will match in all recursive child nodes and return matching nodes.

  • If relationship is decendant, it will match in all recursive child nodes.

  • If relationship is child, it will match in direct child nodes.

  • If relationship is next sibling, it try to match next sibling node.

  • If relationship is subsequent sibling, it will match in all sibling nodes.

Parameters:

Returns:



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/synvert/core/node_query/compiler/selector.rb', line 38

def query_nodes(node)
  return find_nodes_by_relationship(node) if @relationship

  if node.is_a?(::Array)
    return node.flat_map { |child_node| query_nodes(child_node) }
  end

  return find_nodes_by_goto_scope(node) if @goto_scope

  nodes = []
  nodes << node if match?(node)
  if @basic_selector
    node.recursive_children do |child_node|
      nodes << child_node if match?(child_node)
    end
  end
  nodes
end

#to_sObject



57
58
59
60
61
62
63
64
65
# File 'lib/synvert/core/node_query/compiler/selector.rb', line 57

def to_s
  result = []
  result << "#{@goto_scope} " if @goto_scope
  result << "#{@relationship} " if @relationship
  result << @rest.to_s if @rest
  result << @basic_selector.to_s if @basic_selector
  result << ":#{@pseudo_class}(#{@pseudo_selector})" if @pseudo_class
  result.join('')
end