Sha256: a97c13c8bb7d53cc8f6200b9803bfa9bc870dca6f4b7e2397ff552b55862f248

Contents?: true

Size: 830 Bytes

Versions: 10

Compression:

Stored size: 830 Bytes

Contents

require 'facets/proc/bind'

class Proc

  # Convert Proc to method.
  #
  #   plusproc = lambda { |x| x + 1 }
  #   plusproc.to_method(self, 'foo')
  #   X.new.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
      (class << object; self; end).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 10 versions & 1 rubygems

Version Path
facets-2.8.4 lib/core/facets/proc/to_method.rb
facets-2.8.3 lib/core/facets/proc/to_method.rb
facets-2.8.2 lib/core/facets/proc/to_method.rb
facets-2.8.1 lib/core/facets/proc/to_method.rb
facets-2.8.0 lib/core/facets/proc/to_method.rb
facets-2.7.0 lib/core/facets/proc/to_method.rb
facets-2.6.0 lib/core/facets/proc/to_method.rb
facets-2.5.0 lib/core/facets/proc/to_method.rb
facets-2.5.1 lib/core/facets/proc/to_method.rb
facets-2.5.2 lib/core/facets/proc/to_method.rb