Brad Ediger
"Advanced Rails"
new.a_method # => #
The Rails scaffold generator provides a good example of the use of bindings:
class ScaffoldingSandbox
include ActionView::Helpers::ActiveRecordHelper
attr_accessor :form_action, :singular_name, :suffix, :model_instance
28 | Chapter 1: Foundational Techniques
def sandbox_binding
binding
end
# ...
end
ScaffoldingSandbox is a class that provides a clean environment from which to render
a template. ERb can render templates within the context of a binding, so that an
API is available from within the ERb templates.
part_binding = template_options[:sandbox].call.sandbox_binding
# ...
ERB.new(File.readlines(part_path).join,nil,'-').result(part_binding)
Earlier I mentioned that blocks are closures. A closure??™s binding represents its
state??”the set of variables and methods it has access to. We can get at a closure??™s
binding with the Proc#binding method:
def var_from_binding(&b)
eval("var", b.binding)
end
var = 123
var_from_binding {} # => 123
var = 456
var_from_binding {} # => 456
Here we are only using the Proc as a method by which to get the binding. By accessing
the binding (context) of those blocks, we can access the local variable var with a
simple eval against the binding.
Introspection and ObjectSpace: Examining Data and Methods at
Runtime
Ruby provides many methods for looking into objects at runtime. There are object
methods to access instance variables.
Pages:
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58