File: element_matcher.rb

package info (click to toggle)
ruby-mechanize 2.7.6-1%2Bdeb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,480 kB
  • sloc: ruby: 11,380; makefile: 5; sh: 4
file content (68 lines) | stat: -rw-r--r-- 1,781 bytes parent folder | download | duplicates (2)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module Mechanize::ElementMatcher

  def elements_with singular, plural = "#{singular}s"
    class_eval <<-CODE
      def #{plural}_with criteria = {}
        selector = method = nil
        if String === criteria then
          criteria = {:name => criteria}
        else
          criteria = criteria.each_with_object({}) { |(k, v), h|
            case k = k.to_sym
            when :id
              h[:dom_id] = v
            when :class
              h[:dom_class] = v
            when :search, :xpath, :css
              if v
                if method
                  warn "multiple search selectors are given; previous selector (\#{method}: \#{selector.inspect}) is ignored."
                end
                selector = v
                method = k
              end
            else
              h[k] = v
            end
          }
        end

        f = select_#{plural}(selector, method).find_all do |thing|
          criteria.all? do |k,v|
            v === thing.__send__(k)
          end
        end
        yield f if block_given?
        f
      end

      def #{singular}_with criteria = {}
        f = #{plural}_with(criteria).first
        yield f if block_given?
        f
      end

      def #{singular}_with! criteria = {}
        f = #{singular}_with(criteria)
        raise Mechanize::ElementNotFoundError.new(self, :#{singular}, criteria) if f.nil?
        yield f if block_given?
        f
      end

      def select_#{plural} selector, method = :search
        if selector.nil? then
          #{plural}
        else
          nodes = __send__(method, selector)
          #{plural}.find_all do |element|
            nodes.include?(element.node)
          end
        end
      end

      alias :#{singular} :#{singular}_with
    CODE
  end

end