# TITLE: # Proc Bind # # LOG: # - 2006-12-27 (trans) Deprecated use of TemporaryMethods module # class Proc # Bind a proc to an object. Returns a Method. # # The block's #to_s method (same as #inspect) is # used for the temporary method label defined in # the Object class. # # Note this dynamically loads thread.so if used. #-- # But I'm not so sure it is thread critical anymore. #++ def bind(object=nil) require 'thread' object = object || eval("self", self) block = self store = Object begin old, Thread.critical = Thread.critical, true @n ||= 0; @n += 1 name = "_bind_#{@n}#{block.object_id}" store.module_eval do define_method name, &block end meth = object.method(name) ensure store.module_eval do remove_method name #rescue nil #undef_method name #rescue nil end Thread.critical = old end return meth end # Convert Proc to method. # 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 TestProc < 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 def test_memory_leak a = 2 tproc = lambda { |x| x + a } 100.times { tmethod = tproc.to_method assert_equal( 3, tmethod.call(1) ) } meths = ( Object.instance_methods + Object.public_instance_methods + Object.private_instance_methods + Object.protected_instance_methods ) meths = meths.select{ |s| s.to_s =~ /^_bind_/ } #meths = Symbol.all_symbols.select { |s| s.to_s =~ /^_bind_/ } # why ? assert_equal( 0, meths.size ) end end =end