Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

28 | Chapter 1: Foundational Techniques


def sandbox_binding
binding
end

#...
end

ScaffoldingSandboxis a class that provides a clean environment from which to ren-
der 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 theProc#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 theProcas a method by which to get the binding. By access-
ing the binding (context) of those blocks, we can access the local variablevarwith a
simpleeval 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. These methods break encapsulation, so use
them with care.


class C
def initialize
@ivar = 1
end
end

c = C.new
c.instance_variables # => ["@ivar"]
c.instance_variable_get(:@ivar) # => 1

c.instance_variable_set(:@ivar, 3) # => 3
c.instance_variable_get(:@ivar) # => 3
Free download pdf