SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Thursday, October 29, 2009

Binding objects in ruby

The RDOC(standard Ruby documentation format)page for ERB states that the result method of an ERB instance takes a Binding object.

Binding doesn't support any methods beyond those provided by Object.Binding objects are used to represent the visible scope from some location or we can say encapsulate the execution context at some particular place in the code and retain this context for future use.They have no methods because they are intended to be opaque.We can capture the current bindings at any time with the binding kernel method.

mybinding=binding()

This binding can be passed to a very few other methods, one which is eval.

def binding_with_ex
ex = 21
return binding
end

ge=binding_with_ex
eval("ex")
will return the error NameError: undefined local variable or method `b' for main:Object
eval("ex",ge)
=>21

class Genbinder
def initialize(n)
@val=n ** 2
end
def fetchbind
return binding()
end
end

f1=Genbinder.new(3)
f2=Genbinder.new(4)
b1=f1.fetchbind
b2=f2.fetchbind
a=eval("@val",b1)
b=eval("@val",b2)
puts "The recovered value is #{a} #{b}"

The recovered value is 9 16
So a Binding object remembers all the variables you could see at the time it was cre
ated.By accepting a Binding object, ERB lets you determine in exactly what context your embedded Ruby expressions are evaluated

No comments :

Post a Comment