mercredi 16 mars 2016

What is the difference between binding and the top-level object in irb/ruby?

Here are two code snippets:

require 'erb'

weekday = Time.now.strftime('%A')
simple_template = "Today is <%= weekday %>."

renderer = ERB.new(simple_template)
puts output = renderer.result()

and this one:

require 'erb'

weekday = Time.now.strftime('%A')
simple_template = "Today is <%= weekday %>."

renderer = ERB.new(simple_template)
puts output = renderer.result(binding)

That outputs:

puts output = renderer.result(binding)
Today is Wednesday.
=> nil

The second one works but the first one does not.

Here is a quote that describes the first code:

ERB only processes the template when result is called. This means that the output will show the values of variables as they are at the moment when the result is rendered, not when the ERB object was defined.

The code shown above will fail almost anywhere other than in a simple script. ERB gets variables from a Binding, an object that provides access to the instance methods and variables that are owned by another object. If you do not specify a Binding, the result() method gets a Binding from the top-level object, which will probably own very little. Fortunately, every Ruby class has a private binding() instance method to provide Bindings that points to itself, so we can easily extend any object to provide ERB with a Binding.

How is the binding (used in the second code block) different from the top level object (used in the first)

Aucun commentaire:

Enregistrer un commentaire