Class: Rusty::Selector::CSS

Inherits:
Object
  • Object
show all
Defined in:
lib/rusty/selector.rb

Overview

A simple, nokogiri based CSS matcher.

Direct Known Subclasses

CachedCSS

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(selector) ⇒ CSS

Create selector



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rusty/selector.rb', line 16

def initialize(selector)
  @name = @selector = selector

  # == special case: "*"
  #
  # The "*" selector matches all nodes, and Nokogiri::XML::Node#css returns 
  # a huge array of nodes, which R::S::CSS#match? would have to walk through.
  # Implementing that special case speeds up things by ~10% in the google 
  # example, and reduces memory load.
  #
  # Note: by defining it directly on <self> this special case implementation
  # also overrides match? methods defined in subclasses.
  if @selector == "*"
    def self.match?(node); !node.nil?; end
  end
end

Instance Attribute Details

#matcherObject (readonly)

Returns the value of attribute matcher.



13
14
15
# File 'lib/rusty/selector.rb', line 13

def matcher
  @matcher
end

Instance Method Details

#match?(node) ⇒ Boolean

Does this selector matches a specific node?

Returns:

  • (Boolean)


47
48
49
50
51
# File 'lib/rusty/selector.rb', line 47

def match?(node)
  return false unless node
  
  node.document.css(@selector).include?(node)
end

#weightObject

The weight of the selector; is close to, but not exactly as CSS’s weight definition.



35
36
37
38
39
40
41
42
43
44
# File 'lib/rusty/selector.rb', line 35

def weight
  @weight ||= @selector.split(/\s+/).inject(0) do |weight, part|
      weight += case part
        when /#/          then 1_000_000 # part with an ID, much much weight
        when /\./         then     1_000 # selector with a class
        when /^[a-zA-Z_]/ then     1_000 # node name
        else                           1
        end
    end
end