Proc#Bind with Bobby Wilson

The Friday before I left Floyd, I had the opportunity to sit down with Bobby Wilson of Entryway. Bobby and I had been hacking earlier on a hypothesis of mine that ActiveSupport’s Proc#bind could be used effectively to write a DSL instead of somewhat more evil/ugly approaches using Object#instance_eval. Ironically, I found earlier this week that Shoulda already does just that. However, it was fun coming to the same conclusion on my own.

Proc#bind is a funny beast. It effectively converts a Proc into a Method object where self refers to the parameter passed to Proc#bind.

class Proc #:nodoc:
  def bind(object)
    block, time = self, Time.now
    (class << object; self end).class_eval do
      methodname = "bind#{time.to_i}_#{time.usec}"
      definemethod(methodname, &block)
      method = instancemethod(methodname)
      removemethod(methodname)
      method
    end.bind(object)
  end
end
  

Here’s how it works:

  1. Defines a method on self’s (a Proc) singleton class using the Proc itself as the method implementation
  2. Grabs a handle to the UnboundMethod representing the Proc
  3. Removes the method from the Proc’s singleton class (but we still have the UnboundMethod from step 2)
  4. Binds the UnboundMethod to the object passed to Proc#bind, returning a Method object

Afterward, Bobby and I sat down to BS for a bit about how much we needed beer (hey, it was Friday evening), discuss Proc#bind, and the merits of describing oneself to non-software craftsman as a software craftsman.

Interview with Bobby Wilson from Evan Light on Vimeo.

Posted by evan on Wednesday, November 04, 2009

blog comments powered by Disqus