Sha256: 59b1bc9777a42d59fae4ae929941295a4e1e804acb1d8f8dc539b2933df6d4ff

Contents?: true

Size: 1.89 KB

Versions: 9

Compression:

Stored size: 1.89 KB

Contents

module Nokogiri
  module Decorators
    module Hpricot
      module NodeSet

        # Select nodes matching the supplied rule.
        # Note that positional rules (like <tt>:nth()</tt>) aren't currently supported.
        #
        # example: 
        #   node_set.filter('.ohmy')          # selects nodes from the set with class "ohmy"
        #   node_set.filter('a#link2')        # selects nodes from the set with child node <a id='link2'>
        #   node_set.filter('a[@id="link2"]') # selects nodes from the set with child node <a id='link2'>
        def filter(rule)
          filter_transformer( lambda {|j| j}, rule ) # identity transformer
        end

        # The complement to filter, select nodes <em>not</em> matching the supplied rule.
        # Note that positional rules (like <tt>:nth()</tt>) aren't currently supported.
        #
        # See filter for examples.
        #
        # Also note that you can pass a XML::Node object instead of a
        # rule to remove that object from the node set (if it is
        # present):
        #    node_set.not(node_to_exclude) # selects all nodes EXCEPT node_to_exclude
        #
        def not(rule)
          filter_transformer( lambda {|j| !j}, rule ) # negation transformer
        end

      private
        def filter_transformer(transformer, rule)
          sub_set = XML::NodeSet.new(document)
          document.decorate(sub_set)

          if rule.is_a?(XML::Node)
            each { |node| sub_set << node if transformer.call(node == rule) }
            return sub_set
          end

          ctx = CSS::Parser.parse(rule.to_s)
          visitor = CSS::XPathVisitor.new
          visitor.extend(Hpricot::XPathVisitor)
          each do |node|
            if transformer.call(node.at(".//self::" + visitor.accept(ctx.first)))
              sub_set << node
            end
          end
          sub_set
        end          
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
nokogiri-1.0.6-x86-mswin32-60 lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.0.6 lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.0.7 lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.1.0 lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.0.7-x86-mswin32-60 lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.1.0-x86-mswin32-60 lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.1.1-x86-mswin32-60 lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.1.1-java lib/nokogiri/decorators/hpricot/node_set.rb
nokogiri-1.1.1 lib/nokogiri/decorators/hpricot/node_set.rb