Evaluating Inside a Binding

suggest change

Ruby keeps local variables and self in a Binding. Call Kernel#binding to capture the current scope, and Binding#eval to run a string there.

b = proc do
  local_variable = :local
  binding
end.call

b.eval "local_variable" #=> :local
def fake_class_eval(klass, source = nil, &block)
  class_binding = klass.send(:eval, "binding")

  if block
    # A block keeps the scope where it was written. Calling it does not
    # make `def` define methods on klass. class_eval does.
    klass.class_eval(&block)
  else
    class_binding.eval(source)
  end
end

class Example
end

fake_class_eval Example, <<-BLOCK
  def self.foo
    :foo
  end
BLOCK

fake_class_eval Example do
  def bar
    :bar
  end
end

Example.foo       #=> :foo
Example.new.bar   #=> :bar

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents