Magical .send() in Ruby

I have been wanting to write this article for quite sometime now and today is when I finally managed to chuck all errands and pay my dues to this simple yet MAGICAL method. Earlier this year I started to work on a project where I had to use Ruby with Watir-webdriver for automation. Never known Ruby and the drastically changing market and the client demanded that I write the automation framework in Ruby. Majorly because we wanted to implement BDD (Behaviour driven development) using cucumber which is written in Ruby.
I wanted to design a framework where I could dynamically call methods based on parameters and then be able to pass arguments too, parametrically. After doing some research I stumbled upon .send() method. send( ) is an instance method of the Object class. Object is the default root of all Ruby objects. Object inherits from BasicObject which allows creating alternate object hierarchies. Methods on object are available to all classes unless explicitly overridden. The first argument to send( ) is the message that you're sending to the object - that is, the name of a method. You can use a string or a symbol, but symbols are preferred. Any remaining arguments are simply passed on to the method.
For instance:
The flexibility with this method is that now the Method Name and arguments both are now parameterized.
Advantage and implementation:
While writing a framework and scripting ,one of the important steps is to identify page objects. These objects are then used in methods and to perform operations such as clicks, extracting innerHTML and manipulation of HTML attributes . PageObjects are present in .yml file and a ReusableMethods.rb file lays down implementation of the previously mentioned operations. Trick is to specify the TYPE of object that you are interacting with and its locator
.yml
ReusableMethods.rb
With send( ), the name of the method that you want to call becomes just a regular argument. You can wait literally until the very last moment to decide which method to call, while the code is running. elementType and selector are the reusable method and html locators respectively.

Happy scripting… :)

Comments

Popular Posts