Sha256: 85cca8f28d7cbe40e5194849694d6d1192741dd8d970f715d8b40d30220e52c0

Contents?: true

Size: 827 Bytes

Versions: 7

Compression:

Stored size: 827 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

7 entries across 7 versions & 2 rubygems

Version Path
facets-2.4.0 lib/facets/proc/to_method.rb
facets-2.4.1 lib/facets/proc/to_method.rb
facets-2.4.2 lib/core/facets/proc/to_method.rb
facets-2.4.3 lib/core/facets/proc/to_method.rb
facets-2.4.4 lib/core/facets/proc/to_method.rb
facets-2.4.5 lib/core/facets/proc/to_method.rb
mack-facets-0.8.2 lib/gems/facets-2.4.5/lib/core/facets/proc/to_method.rb