Reputation: 5705
As an example, I’d like to get my browser’s user agent as output from http://www.useragentstring.com/ and store it in a variable. Currently, I can do it in multiple lines
require 'watir'
b = Watir::Browser.new(:chrome)
b.goto('http://www.useragentstring.com/')
agent = b.textarea.text
b.close
Ideally, I’d like to do it in a single line. Something like
require 'watir'
agent = Watir::Browser.new(:chrome).goto('http://www.useragentstring.com/').textarea.text
But that fails with
NoMethodError: undefined method `textarea' for "http://www.useragentstring.com/":String`
So while the goto
part works, the rest doesn’t. Since watir
lets us do things like wait_until_present.click
, I’m hoping there’s some way to chain these methods as well. Is this even possible?
Upvotes: 0
Views: 159
Reputation: 46846
You can make anything chain-able by using the tap
method. As described by the Ruby Docs:
Yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.
That means that you can use tap
to call goto
and still have the Watir::Browser
instance for calling textarea
:
agent = Watir::Browser.new(:chrome).tap{ |b| b.goto('http://www.useragentstring.com/') }.textarea.text
Upvotes: 3
Reputation: 2183
Though goto
method does not support chaining you can make your custom method for Watir::Browser
like following
class Watir::Browser
def chain_goto(url)
goto(url)
self
end
end
Then you can use that like
Watir::Browser.new(:firefox).chain_goto('http://www.useragentstring.com/').textarea.text
.
So the complete code will be like
require 'watir'
class Watir::Browser
def chain_goto(url)
goto(url)
self
end
end
b = Watir::Browser.new(:firefox).chain_goto('http://www.useragentstring.com/'.textarea.text
Upvotes: 1