Method: Object#instance_exec

Defined in:
lib/core/facets/kernel/instance_exec.rb

#instance_exec(*args, &block) ⇒ Object

Evaluate the block with the given arguments within the context of this object, so self is set to the method receiver.

From Mauricio’s eigenclass.org/hiki/bounded+space+instance_exec

This version has been borrowed from Rails for compatibility sake.

NOTE: This is not a common core extension (due to the use of thread.rb) and is not loaded automatically when using require 'facets'. However it is a core method in Ruby 1.9, so this only matters for users of Ruby 1.8.x or below.

Uncommon:

  • require ‘facets/kernel/instance_exec’



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/core/facets/kernel/instance_exec.rb', line 27

def instance_exec(*args, &block)
  begin
    old_critical, Thread.critical = Thread.critical, true
    n = 0
    n += 1 while respond_to?(method_name = "__instance_exec#{n}")
    InstanceExecMethods.module_eval { define_method(method_name, &block) }
  ensure
    Thread.critical = old_critical
  end

  begin
    __send__(method_name, *args)
  ensure
    InstanceExecMethods.module_eval { remove_method(method_name) } rescue nil
  end
end