Sha256: 1ba8344a82b3244b1c79ea16aa20047960ed63adadb80bd8a2a9454dbdb133f7

Contents?: true

Size: 1.61 KB

Versions: 16

Compression:

Stored size: 1.61 KB

Contents

#--
# Credit for #to_method goes to Forian Gross (flgr).
#--

require 'thread'

class Proc

  MethodMutexes = Hash.new do |hash, key|
    hash[key] = Mutex.new
  end

  # Creates a local method based on a Proc.
  def to_method(name=nil)
    name ||= "!to_method_temp#{self.id}"
    recv = eval("self", self)
    klass = recv.class
    MethodMutexes[klass => name].synchronize do
      begin
        klass.send(:define_method, name, &self)
        return recv.method(name)
      ensure
        klass.send(:remove_method, name) if not name
      end
    end
  end

end

=begin
  # Alternate. I assume this is less "safe" then the above.
  def to_method
      # get the object that this proc is bound to
    obj = eval 'self', self.binding
      # get the virtual class for the object
    obj_class = class << obj; self; end
    proc = self
      # define the method. A normally invalid method name was chosen to minimize
      # the chance of a collision. Store the newly created method away.
    obj_class.instance_eval{define_method(:" ", &proc)}
    method = obj.method(:" ")
      # remove the method, and return it.
    obj_class.instance_eval{remove_method(:" ")}
    method
  end
=end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCProc < Test::Unit::TestCase

    def test_to_method
      a = 2
      tproc = proc { |x| x + a }  
      tmethod = tproc.to_method(:tryit)
      assert_equal( 3, tmethod.call(1) )
      assert_respond_to( self, :tryit )
      assert_equal( 3, tryit(1) )
    end

  end

=end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/proc/to_method.rb
facets-0.9.0 lib/nano/proc/to_method.rb
facets-1.0.3 packages/core/lib/facet/proc/to_method.rb
facets-1.2.1 lib/facets/core/proc/to_method.rb
facets-1.2.0 lib/facets/core/proc/to_method.rb
facets-1.3.0 lib/facets/core/proc/to_method.rb
facets-1.1.0 lib/facet/proc/to_method.rb
facets-1.3.3 lib/facets/core/proc/to_method.rb
facets-1.3.1 lib/facets/core/proc/to_method.rb
facets-1.3.2 lib/facets/core/proc/to_method.rb
facets-1.4.0 lib/facets/core/proc/to_method.rb
facets-1.4.1 lib/facets/core/proc/to_method.rb
facets-1.4.2 lib/facets/core/proc/to_method.rb
facets-1.4.3 lib/facets/core/proc/to_method.rb
facets-1.4.5 lib/facets/core/proc/to_method.rb
facets-1.4.4 lib/facets/core/proc/to_method.rb