Charles Nutter wrote:
> Thoughts? Comments? This version is obviously not threadsafe, but it
> gets you pretty close to singleton methods without requiring singleton
> classes.

What if you are defining a singleton method to override a method which 
already exists in the class? It's fixable...

module Singletonizer
  def attach_method(name, &block)
    (@attached_methods ||= {})[name] = block
    class_method = "__class_#{name}"
    return if respond_to? class_method
    if respond_to? name
      self.class.class_eval "alias :#{class_method} :#{name}"
    else
      self.class.class_eval <<-RUBY
        def #{class_method}(*args)
          ex = NoMethodError.new("undefined method `#{name}' for 
\#{self.inspect}:\#{self.class}")
          ex.set_backtrace caller(2)
          raise ex
        end
      RUBY
    end
    self.class.class_eval <<-RUBY, __FILE__, __LINE__
      def #{name}(*args)
        if (defined? @attached_methods) && (block = 
@attached_methods[:#{name}])
          instance_exec(*args, &block)
        else
          __class_#{name}(*args)
        end
      end
    RUBY
  end
end

...unless someone comes along and decides to change the definition in 
the class :-(

I note that using the block syntax for defining singleton methods means 
that singleton methods can't take a block. But that's not an problem if 
this is just a demo of something which will take place under the hood.
-- 
Posted via http://www.ruby-forum.com/.