Class: Object

Inherits:
BasicObject
Includes:
InstanceExecMethods
Defined in:
lib/ruco/core_ext/object.rb,
lib/ruco/core_ext/object.rb

Defined Under Namespace

Modules: InstanceExecMethods

Instance Method Summary collapse

Instance Method Details

#delegate(*methods) ⇒ Object

copy from active_support



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/ruco/core_ext/object.rb', line 3

def delegate(*methods)
  options = methods.pop
  unless options.is_a?(Hash) && to = options[:to]
    raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
  end

  methods.each do |method|
    module_eval(<<-EOS, "(__DELEGATION__)", 1)
def #{method}(*args, &block)
#{to}.__send__(#{method.inspect}, *args, &block)
end
EOS
  end
end

#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



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ruco/core_ext/object.rb', line 29

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