Re-binding Proc

Is there a way to call a proc while passing in the binding/scope for
'self'? I found an un-responded-to question on this (ruby-talk:12794)
in 2001 which implies that, at least then, there was no way to do it.

What I'm doing:
class Foo
  @@handlers = {}

  def self.handle_type( type, &proc )
    @@handlers[ type ] = proc
  end

  attr_reader :name
  def initialize( name )
    @name = name
  end

  def do_thing( type )
    @@handlers[ type ].call( self )
  end
end

Foo.handle_type( :showname ){ |me|
  puts "My name is '#{me.name}'"
}

f = Foo.new( 'f' )
f.do_thing( :showname )
#=> My name is 'f'

What I'd like to do instead:

Foo.handle_type( :showname ){
  puts "My name is '#{self.name}'"
}

Damn, hit send too soon. **continues**

I realize that I can do this by defining a method (as below), but for
some reason that feels bad to me. I'd like to do it with Proc objects,
if possible.

# Works by spamming the method namespace.
class Foo
  def self.handle_type( type, &proc )
    define_method( "dothing_#{type}", &proc )
  end
  # ...
  def do_thing( type )
    send "dothing_#{type}"
  end
end

Phrogz wrote:

Is there a way to call a proc while passing in the binding/scope for
'self'? I found an un-responded-to question on this (ruby-talk:12794)
in 2001 which implies that, at least then, there was no way to do it.

I may be just feeling light-headed from COBOL, but
would #instance_eval not work here?

What I'm doing:
class Foo
  @@handlers = {}

  def self.handle_type( type, &proc )
    @@handlers[ type ] = proc
  end

  attr_reader :name
  def initialize( name )
    @name = name
  end

  def do_thing( type )
    @@handlers[ type ].call( self )

      instance_eval &@@handlers[type]

  end
end

Foo.handle_type( :showname ){ |me|
  puts "My name is '#{me.name}'"
}

  Foo.handle_type(:showname) {puts "My name is #{self.name}"}

···

f = Foo.new( 'f' )
f.do_thing( :showname )
#=> My name is 'f'

What I'd like to do instead:

Foo.handle_type( :showname ){
  puts "My name is '#{self.name}'"
}

--
Posted via http://www.ruby-forum.com/\.