Skip to content

Instantly share code, notes, and snippets.

@headius
Created March 15, 2010 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save headius/333174 to your computer and use it in GitHub Desktop.
Save headius/333174 to your computer and use it in GitHub Desktop.
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
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