Adding Methods to Ruby Objects

Yesterday, during lecture, I tried (and failed) to add a method to a Ruby object.

Today, I picked up a Ruby book and learned how to add what are called singleton methods to a Ruby object.

Recall that Cucumber creates a new object called "world" to be used as the context for running all of the step definitions associated with a given scenario. At the start of each scenario, cucubmer essentially invokes code that looks like this

world = Object.new

This line gives us a default Ruby object, an instance of the Object class. The methods that represent step definitions are then added to this object. Imagine that behind the scenes, cucubmer called each of the relevant step definitions something like this: step1, step2, step3, etc.

Then, to execute a scenario, cucumber would essentially do the following:

world = Object.new
<add the step1, step2, etc. methods to world>
world.step1(args)
world.step2(args)

With that information as context, here's the method for adding a singleton method to an object in Ruby:

world1 = Object.new
world2 = Object.new

def world.hello
  puts "HELLO!"
end

world1.hello // output equals "HELLO!"
world2.hello // No Such Method exception

We have two instances of Object but only one of them (world1) has had a hello method added to it.

Now, in truth, Cucumber likely generates a class for the world object dynamically and uses a class method called define_method to add the step definition methods to the world object but the effect is the same: the step definitions become methods on the world object and the scenario is then executed by simply calling each of these methods in the correct order passing in the appropriate arguments.

© University of Colorado, Boulder 2011