Module: Gemmy::Patches::ProcPatch::InstanceMethods::ToMethod

Defined in:
lib/gemmy/patches/proc_patch.rb

Instance Method Summary collapse

Instance Method Details

#to_method(object, name = nil) ⇒ Object

facets converts a proc to a method on an object object = Object.__new__ function = lambda { |x| x + 1 } function.to_method(object, ‘foo’) object.foo(1) #=> 2



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/gemmy/patches/proc_patch.rb', line 25

def to_method(object, name=nil)
  ##object = object || eval("self", self)
  block, time = self, Time.now
  method_name = name || "__bind_#{time.to_i}_#{time.usec}"
  begin
    object.singleton_class.class_eval do
      define_method(method_name, &block)
      method = instance_method(method_name)
      remove_method(method_name) unless name
      method
    end.bind(object)
  rescue TypeError
    object.class.class_eval do
      define_method(method_name, &block)
      method = instance_method(method_name)
      remove_method(method_name) unless name
      method
    end.bind(object)
  end
end