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 endEnjoy!
Labels: Metaprogramming, Ruby
0 Comments:
Post a Comment
<< Home