Need #define_singleton_method in Ruby 1.8.7?
I recently found myself in need of #define_singleton_method
for a project that is still running Ruby 1.8.7—yeah, yeah, I know... But I'm not the only one. Of course, if it is in the context of a Ruby on Rails application, the core team was nice enough to back-port Object#singleton_class
for dealing with situations like this. However, outside of a Rails application, you may still need something to get at the singleton class (or metaclass, if you prefer that terminology).
Thankfully, Ruby's open classes allow us to work some magic like so:
class Object
def singleton_class
class << self; self; end
end
end
And, voila! You can now do something like this:
some_object.singleton_class.send :define_method, :method_name { method.body }
Happy coding!
Written by Mark Coates
Related protips
1 Response
Hi Mark. What about defining it on modules?
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby 1.8.7
Authors
barnabyalter
3.577K
bitpimpin
1.754K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#