Class: REXML::CSSSelector::Queries::NthChildOfQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/rexml/css_selector/queries/nth_child_of_query.rb

Instance Method Summary collapse

Constructor Details

#initialize(cont:, a:, b:, query:) ⇒ NthChildOfQuery

Returns a new instance of NthChildOfQuery.



7
8
9
10
11
12
# File 'lib/rexml/css_selector/queries/nth_child_of_query.rb', line 7

def initialize(cont:, a:, b:, query:)
  @cont = cont
  @a = a
  @b = b
  @query = query
end

Instance Method Details

#call(node, context) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rexml/css_selector/queries/nth_child_of_query.rb', line 14

def call(node, context)
  return false unless context.adapter.element?(node)

  parent = context.adapter.get_parent_node(node)
  return false unless parent

  matched_children = context.cache[[object_id, parent.object_id]]
  unless matched_children
    children = context.adapter.get_children_elements(parent)
    matched_children = children.filter { @query.call(_1, context) }
    context.cache[[object_id, parent.object_id]] = matched_children
  end

  index = matched_children.index(node)
  return false unless index
  index += 1

  if @a.zero?
    index == @b && @cont.call(node, context)
  else
    ((index - @b) % @a).zero? && (index - @b) / @a >= 0 && @cont.call(node, context)
  end
end