Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 66 lines (51 sloc) 1.686 kb
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
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| Webrat::XML.all_inner_text(a).length <=> Webrat::XML.all_inner_text(b).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(Webrat::XML.all_inner_text(link)) =~ matcher ||
        replace_nbsp_ref(Webrat::XML.inner_html(link)) =~ matcher ||
        Webrat::XML.attribute(link, "title")=~ matcher
      end

      def matches_id?(link)
        if @value.is_a?(Regexp)
          (Webrat::XML.attribute(link, "id") =~ @value) ? true : false
        else
          (Webrat::XML.attribute(link, "id") == @value) ? true : false
        end
      end
  
      def link_elements
        Webrat::XML.xpath_search(@dom, *Link.xpath_search)
      end
  
      def replace_nbsp(str)
        str.gsub([0xA0].pack('U'), ' ')
      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
Something went wrong with that request. Please try again.