File: substitution_context.rb

package info (click to toggle)
ruby-rails-dom-testing 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 156 kB
  • sloc: ruby: 974; makefile: 4
file content (44 lines) | stat: -rw-r--r-- 1,377 bytes parent folder | download
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
# frozen_string_literal: true

module Rails
  module Dom
    module Testing
      module Assertions
        module SelectorAssertions
          class SubstitutionContext # :nodoc:
            def initialize
              @substitute = "?"
            end

            def substitute!(selector, values, format_for_presentation = false)
              selector.gsub @substitute do |match|
                next match[0] if values.empty? || !substitutable?(values.first)
                matcher_for(values.shift, format_for_presentation)
              end
            end

            def match(matches, attribute, matcher)
              matches.find_all { |node| node[attribute] =~ Regexp.new(matcher) }
            end

            private
              def matcher_for(value, format_for_presentation)
                # Nokogiri doesn't like arbitrary values without quotes, hence inspect.
                if format_for_presentation
                  value.inspect # Avoid to_s so Regexps aren't put in quotes.
                elsif value.is_a?(Regexp)
                  "\"#{value}\""
                else
                  value.to_s.inspect
                end
              end

              def substitutable?(value)
                [ Symbol, Numeric, String, Regexp ].any? { |type| value.is_a? type }
              end
          end
        end
      end
    end
  end
end