Sha256: 068aeac87ad2afa732f913459315162f7d6fa6e329de53f1ca507c00ac2d1b4f

Contents?: true

Size: 906 Bytes

Versions: 10

Compression:

Stored size: 906 Bytes

Contents

require 'facets/proc/bind'
require 'facets/kernel/singleton_class'

class Proc

  # Convert Proc to method.
  #
  #   object = Object.new
  #
  #   function = lambda { |x| x + 1 }
  #
  #   function.to_method(object, 'foo')
  #
  #   object.foo(1)  #=> 2
  #
  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

end

Version data entries

10 entries across 9 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/proc/to_method.rb
facets-3.1.0 lib/core/facets/proc/to_method.rb
facets-3.0.0 lib/core/facets/proc/to_method.rb
facets-2.9.3 lib/core/facets/proc/to_method.rb
facets-2.9.2 src/core/facets/proc/to_method.rb
facets-2.9.2 lib/core/facets/proc/to_method.rb
facets-2.9.1 lib/core/facets/proc/to_method.rb
facets-2.9.0 lib/core/facets/proc/to_method.rb
facets-2.9.0.pre.2 lib/core/facets/proc/to_method.rb
facets-2.9.0.pre.1 lib/core/facets/proc/to_method.rb