# CREDIT Forian Gross
# CREDIT Mauricio Fernandez
# CREDIT Thomas Sawyer

require 'facets/core/proc/bind'

class Proc

  def to_method(name=nil, object=nil)
    return bind unless name

    object = object || eval("self", self)
    klass  = object.class
    block  = self

    klass.class_eval do
      define_method name, &block
    end
    object.method(name)
  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

    # This is dependent on other tests! Be aware!

    def test_memory_leak
      a = 2
      tproc = proc { |x| x + a }
      100.times {
        tmethod = tproc.to_method
        assert_equal( 3, tmethod.call(1) )
      }
      meths = Symbol.all_symbols.select { |s| s.to_s =~ /^_bind_/ }
      assert_equal( 1, meths.size )
    end

  end

=end
