lib/watir-webdriver/window_switching.rb in watir-webdriver-0.0.9 vs lib/watir-webdriver/window_switching.rb in watir-webdriver-0.1.0

- old
+ new

@@ -1,55 +1,70 @@ module Watir module WindowSwitching + class NoMatchingWindowFoundException < StandardError + end + def windows(*args) - wins = @driver.window_handles.map do |id| - Window.new(@driver, id) - end + all = @driver.window_handles.map { |id| Window.new(@driver, id) } if args.empty? - wins + all else - filter_windows(args, wins, :select) + filter_windows(args, all, :select) end end def window(*args, &blk) win = filter_windows(args, windows, :find) if win && block_given? win.use(&blk) end - win + win or raise NoMatchingWindowFoundException, args.inspect end private - def filter_windows(args, wins, method) + def filter_windows(args, all, method) sel = extract_selector(args) + if sel.empty? + all.find { |w| w.current? } + end + unless sel.keys.all? { |k| [:title, :url].include? k } - raise ArgumentError, "invalid window selector: #{sel}" + raise ArgumentError, "invalid window selector: #{sel.inspect}" end - wins.send(method) do |win| + all.send(method) do |win| sel.all? { |key, value| value === win.send(key) } end end end # WindowSwitching class Window def initialize(driver, id) @driver, @id = driver, id end - def inspect '#<%s:0x%x id=%s>' % [self.class, hash*2, @id.to_s] end + def ==(other) + return false unless other.kind_of?(self.class) + + @id == other.id + end + alias_method :eql?, :== + + def hash + @id.hash ^ self.class.hash + end + def current? @driver.window_handle == @id end def close @@ -69,10 +84,22 @@ url end def use(&blk) + if current? + yield if block_given? + return self + end + @driver.switch_to.window(@id, &blk) self end + + protected + + def id + @id + end + end # Window end # Watir