Created
March 15, 2010 18:47
-
-
Save headius/333174 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Singletonizer | |
def attach_method(name, &block) | |
unless respond_to? name | |
self.class.class_eval <<-RUBY, __FILE__, __LINE__ | |
def #{name}(*args) | |
if (defined? @attached_methods) && (block = @attached_methods[:#{name}]) | |
instance_exec(*args, &block) | |
else | |
ex = NoMethodError.new("undefined method `#{name}' for \#{self.inspect}:\#{self.class}") | |
ex.set_backtrace caller(1) | |
raise ex | |
end | |
end | |
RUBY | |
end | |
(@attached_methods ||= {})[name] = block | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'singletonizer' | |
class String | |
include Singletonizer | |
end | |
a = 'yum' | |
a.attach_method(:foo) do | |
puts self | |
end | |
a.foo # works | |
'blah'.foo # raises error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment