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(node_type: nil, attribute_list: nil, index: nil, pseudo_class: nil, pseudo_expression: nil) ⇒ Selector

Initialize a Selector.



12
13
14
15
16
17
18
# File 'lib/synvert/core/node_query/compiler/selector.rb', line 12

def initialize(node_type: nil, attribute_list: nil, index: nil, pseudo_class: nil, pseudo_expression: nil)
  @node_type = node_type
  @attribute_list = attribute_list
  @index = index
  @pseudo_class = pseudo_class
  @pseudo_expression = pseudo_expression
end

Instance Method Details

#filter(nodes) ⇒ Object

Filter nodes by index.



21
22
23
24
25
# File 'lib/synvert/core/node_query/compiler/selector.rb', line 21

def filter(nodes)
  return nodes if @index.nil?

  nodes[@index] ? [nodes[@index]] : []
end

#match?(node, _operator = :==) ⇒ Boolean

Check if node matches the selector.



29
30
31
32
33
# File 'lib/synvert/core/node_query/compiler/selector.rb', line 29

def match?(node, _operator = :==)
  (!@node_type || (node.is_a?(::Parser::AST::Node) && @node_type.to_sym == node.type)) &&
    (!@attribute_list || @attribute_list.match?(node)) &&
    (!@pseudo_class || (@pseudo_class == 'has' && @pseudo_expression.match?(node)) || (@pseudo_class == 'not_has' && !@pseudo_expression.match?(node)))
end

#to_sObject



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

def to_s
  result = []
  result << ".#{@node_type}" if @node_type
  result << @attribute_list.to_s if @attribute_list
  result << ":#{@pseudo_class}(#{@pseudo_expression})" if @pseudo_class
  if @index
    result <<
      case @index
      when 0
        ':first-child'
      when -1
        ':last-child'
      when (1..)
        ":nth-child(#{@index + 1})"
      else # ...-1
        ":nth-last-child(#{-@index})"
      end
  end
  result.join('')
end