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, has_expression: nil) ⇒ Selector

Initialize a Selector.

Parameters:



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

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

Instance Method Details

#filter(nodes) ⇒ Object

Filter nodes by index.



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

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

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

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

Check if node matches the selector.

Parameters:

Returns:



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

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

#to_sObject



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

def to_s
  str = ".#{@node_type}#{@attribute_list}"
  return str if !@index && !@has_expression

  return "#{str}:has(#{@has_expression})" if @has_expression

  case @index
  when 0
    str + ':first-child'
  when -1
    str + ':last-child'
  when (1..)
    str + ":nth-child(#{@index + 1})"
  else # ...-1
    str + ":nth-last-child(#{-@index})"
  end
end