File: node.rb

package info (click to toggle)
ruby-nokogiri 1.10.0%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,088 kB
  • sloc: xml: 28,081; ruby: 16,687; java: 13,293; ansic: 4,954; yacc: 265; sh: 76; makefile: 19
file content (52 lines) | stat: -rw-r--r-- 1,369 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
module Nokogiri
  module CSS
    class Node
      ALLOW_COMBINATOR_ON_SELF = [:DIRECT_ADJACENT_SELECTOR, :FOLLOWING_SELECTOR, :CHILD_SELECTOR]

      # Get the type of this node
      attr_accessor :type
      # Get the value of this node
      attr_accessor :value

      # Create a new Node with +type+ and +value+
      def initialize type, value
        @type = type
        @value = value
      end

      # Accept +visitor+
      def accept visitor
        visitor.send(:"visit_#{type.to_s.downcase}", self)
      end

      ###
      # Convert this CSS node to xpath with +prefix+ using +visitor+
      def to_xpath prefix = '//', visitor = XPathVisitor.new
        prefix = '.' if ALLOW_COMBINATOR_ON_SELF.include?(type) && value.first.nil?
        prefix + visitor.accept(self)
      end

      # Find a node by type using +types+
      def find_by_type types
        matches = []
        matches << self if to_type == types
        @value.each do |v|
          matches += v.find_by_type(types) if v.respond_to?(:find_by_type)
        end
        matches
      end

      # Convert to_type
      def to_type
        [@type] + @value.map { |n|
          n.to_type if n.respond_to?(:to_type)
        }.compact
      end

      # Convert to array
      def to_a
        [@type] + @value.map { |n| n.respond_to?(:to_a) ? n.to_a : [n] }
      end
    end
  end
end