Ruby, iOS, and Other Development

A place to share useful code snippets, ideas, and techniques

All code in posted articles shall be considered public domain unless otherwise noted.
Comments remain the property of their authors.

2006-06-11

Class#extract_instance_method and Object#extract_singleton_method

This is sort of kinky, but sometimes it's just what you need. Particularly when extending (rather than including) modules, it is sometimes desirable to preserve, but remove, an existing method. To that end I present:

class Module
  def extract_instance_method(sym)
    if instance_methods(false).include? sym.to_s
      method = instance_method(sym)
      remove_method(sym)
      method
    else
      nil
    end
  end
end

class Object
  def extract_singleton_method(sym)
    metaclass = class << self; self; end
    if method = metaclass.extract_instance_method(sym)
      method.bind(self).to_proc
    else
      nil
    end
  end
end
Enjoy!

Labels: ,

0 Comments:

Post a Comment

<< Home