From 0b6d9c28ea1f07ba09e95ab6f24088d1e5077355 Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Sat, 29 Nov 2008 01:30:23 -0500 Subject: [PATCH] Extracting ButtonLocator object --- lib/webrat/core/locators.rb | 20 ++-------- lib/webrat/core/locators/button_locator.rb | 43 ++++++++++++++++++++++ 2 files changed, 46 insertions(+), 17 deletions(-) create mode 100644 lib/webrat/core/locators/button_locator.rb diff --git a/lib/webrat/core/locators.rb b/lib/webrat/core/locators.rb index fb502b7..e7db3fc 100644 --- a/lib/webrat/core/locators.rb +++ b/lib/webrat/core/locators.rb @@ -94,24 +94,10 @@ module Webrat end def find_button(value) #:nodoc: - field_elements = Webrat::XML.xpath_search(dom, *ButtonField.xpath_search) + require "webrat/core/locators/button_locator" - field_element = field_elements.detect do |field_element| - value.nil? || - (value.is_a?(Regexp) && Webrat::XML.attribute(field_element, "id") =~ value) || - (!value.is_a?(Regexp) && Webrat::XML.attribute(field_element, "id") == value.to_s) || - Webrat::XML.attribute(field_element, "value") =~ /^\W*#{Regexp.escape(value.to_s)}/i || - Webrat::XML.inner_html(field_element) =~ /#{Regexp.escape(value.to_s)}/i || - Webrat::XML.attribute(field_element, "alt") =~ /^\W*#{Regexp.escape(value.to_s)}/i - end - - button = field_by_element(field_element) - - if button - return button - else - raise NotFoundError.new("Could not find button #{value.inspect}") - end + ButtonLocator.new(self, value).locate || + raise(NotFoundError.new("Could not find button #{value.inspect}")) end def find_area(id_or_title) #:nodoc: diff --git a/lib/webrat/core/locators/button_locator.rb b/lib/webrat/core/locators/button_locator.rb new file mode 100644 index 0000000..6586363 --- /dev/null +++ b/lib/webrat/core/locators/button_locator.rb @@ -0,0 +1,43 @@ +class ButtonLocator + + def initialize(scope, value) + @scope = scope + @value = value + end + + def locate + @scope.field_by_element(button_element) + end + + def button_element + button_elements.detect do |element| + @value.nil? || + matches_id?(element) || + matches_value?(element) || + matches_html?(element) || + matches_alt?(element) + end + end + + def matches_id?(element) + (@value.is_a?(Regexp) && Webrat::XML.attribute(element, "id") =~ @value) || + (!@value.is_a?(Regexp) && Webrat::XML.attribute(element, "id") == @value.to_s) + end + + def matches_value?(element) + Webrat::XML.attribute(element, "value") =~ /^\W*#{Regexp.escape(@value.to_s)}/i + end + + def matches_html?(element) + Webrat::XML.inner_html(element) =~ /#{Regexp.escape(@value.to_s)}/i + end + + def matches_alt?(element) + Webrat::XML.attribute(element, "alt") =~ /^\W*#{Regexp.escape(@value.to_s)}/i + end + + def button_elements + Webrat::XML.xpath_search(@scope.dom, *Webrat::ButtonField.xpath_search) + end + +end \ No newline at end of file