Sha256: 22ca2b5d5022bbcdf10e5e453785eb56be554c34f5d4d8346f9b765603833e4b

Contents?: true

Size: 1.69 KB

Versions: 16

Compression:

Stored size: 1.69 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)
        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 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 or title or id #{@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

16 entries across 16 versions & 10 rubygems

Version Path
thoughtbot-webrat-0.7.2.pre lib/webrat/core/locators/link_locator.rb
revo-webrat-0.7.0.1 lib/webrat/core/locators/link_locator.rb
webrat-0.7.1 lib/webrat/core/locators/link_locator.rb
davidtrogers-webrat-0.7.0 lib/webrat/core/locators/link_locator.rb
revo-webrat-0.7.0 lib/webrat/core/locators/link_locator.rb
revo-webrat-0.7.1.pre lib/webrat/core/locators/link_locator.rb
webrat-0.7.0 lib/webrat/core/locators/link_locator.rb
darkofabijan-webrat-0.6.1 lib/webrat/core/locators/link_locator.rb
kbaum-webrat-0.5.1 lib/webrat/core/locators/link_locator.rb
kbaum-webrat-0.6.1.pre lib/webrat/core/locators/link_locator.rb
cynergy-webrat-0.6.0 lib/webrat/core/locators/link_locator.rb
webrat-0.6.0 lib/webrat/core/locators/link_locator.rb
radar-webrat-0.5.1.1 lib/webrat/core/locators/link_locator.rb
radar-webrat-0.5.1 lib/webrat/core/locators/link_locator.rb
mkuklis-webrat-0.5.1 lib/webrat/core/locators/link_locator.rb
honkster-webrat-0.6.0 lib/webrat/core/locators/link_locator.rb