Class: Gammo::CSSSelector::AST::Selector::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/gammo/css_selector/ast/selector.rb

Direct Known Subclasses

Type, Universal

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace_prefix: nil, selectors: []) ⇒ Base

Returns a new instance of Base.



31
32
33
34
35
# File 'lib/gammo/css_selector/ast/selector.rb', line 31

def initialize(namespace_prefix: nil, selectors: [])
  @namespace_prefix = namespace_prefix
  @selectors = selectors
  @combinations = []
end

Instance Attribute Details

#selectorsObject

Returns the value of attribute selectors.



29
30
31
# File 'lib/gammo/css_selector/ast/selector.rb', line 29

def selectors
  @selectors
end

Instance Method Details

#combine(selector) ⇒ Object



67
68
69
# File 'lib/gammo/css_selector/ast/selector.rb', line 67

def combine(selector)
  @combinations << selector
end

#evaluate(context) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/gammo/css_selector/ast/selector.rb', line 37

def evaluate(context)
  node_set = NodeSet.new
  search_descendant(context, node_set)

  @combinations.inject(node_set) do |ns, combination|
    duplicates = Set.new
    ns.each_with_object(NodeSet.new) do |node, ret|
      context.node = node
      # TODO: #concat
      combination.evaluate(context).each do |matched|
        ret << matched if duplicates.add?(matched)
      end
    end
  end
end

#match?(context) ⇒ Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/gammo/css_selector/ast/selector.rb', line 71

def match?(context)
  @selectors.all? { |matcher| matcher.match?(context) }
end

#search_descendant(context, node_set) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/gammo/css_selector/ast/selector.rb', line 53

def search_descendant(context, node_set)
  queue = [context]
  until queue.empty?
    current_context = queue.shift
    node_set << current_context.node if match?(current_context)
    current_context.node.children.inject(0) do |i, child|
      next i unless child.kind_of?(Node::Element)
      i += 1
      queue << Context.new(node: child, position: i)
      i
    end
  end
end