From d05001b2d4598b3439da32917598d6e3548022eb Mon Sep 17 00:00:00 2001 From: Tom Stuart Date: Sat, 25 Apr 2009 11:14:56 +0100 Subject: [PATCH] Make LinkLocator#link_element check the length of the actual matching content when deciding which matching link is the shortest --- lib/webrat/core/locators/link_locator.rb | 49 +++++++++++++++++++++-------- 1 files changed, 35 insertions(+), 14 deletions(-) diff --git a/lib/webrat/core/locators/link_locator.rb b/lib/webrat/core/locators/link_locator.rb index 426c527..cca6a4a 100644 --- a/lib/webrat/core/locators/link_locator.rb +++ b/lib/webrat/core/locators/link_locator.rb @@ -10,33 +10,54 @@ module Webrat end def link_element - matching_links.min { |a, b| Webrat::XML.all_inner_text(a).length <=> Webrat::XML.all_inner_text(b).length } + matching_links_with_content.keys.min { |a, b| matching_links_with_content[a].length <=> matching_links_with_content[b].length } end def matching_links - @matching_links ||= link_elements.select do |link_element| - matches_text?(link_element) || - matches_id?(link_element) + @matching_links ||= matching_links_with_content.keys + end + + def matching_links_with_content + @matching_links_with_content ||= link_elements.inject({}) do |matching_links_with_content, link_element| + if matching_content = (matching_content_from_text(link_element) || matching_content_from_id(link_element)) + matching_links_with_content[link_element] = matching_content + end + + matching_links_with_content end end def matches_text?(link) - if @value.is_a?(Regexp) - matcher = @value - else - matcher = /#{Regexp.escape(@value.to_s)}/i - end + !matching_content_from_text(link).nil? + 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 + def matching_content_from_text(link) + matcher = value_matcher + + if + (matching_content = replace_nbsp(Webrat::XML.all_inner_text(link))) =~ matcher || + (matching_content = replace_nbsp_ref(Webrat::XML.inner_html(link))) =~ matcher || + (matching_content = Webrat::XML.attribute(link, "title")) =~ matcher + then + matching_content + end end def matches_id?(link) + matching_content_from_id(link).nil? + end + + def matching_content_from_id(link) + if (matching_content = Webrat::XML.attribute(link, "id")) =~ value_matcher + matching_content + end + end + + def value_matcher if @value.is_a?(Regexp) - (Webrat::XML.attribute(link, "id") =~ @value) ? true : false + matcher = @value else - (Webrat::XML.attribute(link, "id") == @value) ? true : false + matcher = /#{Regexp.escape(@value.to_s)}/i end end -- 1.6.2.2