Sha256: 3d4099180724c21e73974d7fcb5451156b0be45ff166fd71a75d5eb41aff5e64

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

require "webrat/core/locators/locator"

module Webrat
  module Locators

    class LinkLocator < Locator # :nodoc:

      def locate
        Link.load(@session, link_element)
      end

      def link_element
        matching_links.min { |a, b| a.inner_text.length <=> b.inner_text.length }
      end

      def matching_links
        @matching_links ||= link_elements.select do |link_element|
          matches_text?(link_element) ||
          matches_id?(link_element) ||
          matches_class?(link_element)
        end
      end

      def matches_text?(link)
        if @value.is_a?(Regexp)
          matcher = @value
        else
          matcher = /#{Regexp.escape(@value.to_s)}/i
        end

        replace_nbsp(link.inner_text) =~ matcher ||
        replace_nbsp_ref(link.inner_html) =~ matcher ||
        link["title"] =~ matcher
      end

      def matches_id?(link)
        if @value.is_a?(Regexp)
          link["id"] =~ @value ? true : false
        else
          link["id"] == @value ? true : false
        end
      end
      
      def matches_class?(link)
        if @value.is_a?(Regexp)
          link["class"] =~ @value ? true : false
        else
          link["class"].split(%r{\s}).include?(@value) unless link["class"].nil?
        end
      end
      
      def link_elements
        @dom.xpath(*Link.xpath_search)
      end

      def replace_nbsp(str)
        if str.respond_to?(:valid_encoding?)
          if str.valid_encoding?
            str.gsub(/\xc2\xa0/u, ' ')
          else
            str.force_encoding('UTF-8').gsub(/\xc2\xa0/u, ' ')
          end
        else
          str.gsub(/\xc2\xa0/u, ' ')
        end
      end

      def replace_nbsp_ref(str)
        str.gsub('&#xA0;',' ').gsub('&nbsp;', ' ')
      end

      def error_message
        "Could not find link with text, title, id or class #{@value.inspect}"
      end

    end

    def find_link(text_or_title_or_id) #:nodoc:
      LinkLocator.new(@session, dom, text_or_title_or_id).locate!
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
diabolo-webrat-0.5.1 lib/webrat/core/locators/link_locator.rb