Browse files

Added Object#metaclass

  • Loading branch information...
1 parent 89eec91 commit f4f6e57e8c2a446a4a600576f0caf0fb8921ba13 @josh josh committed Jul 16, 2008
1 activesupport/lib/active_support/core_ext/object.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/object/conversions'
require 'active_support/core_ext/object/extending'
require 'active_support/core_ext/object/instance_variables'
+require 'active_support/core_ext/object/metaclass'
require 'active_support/core_ext/object/misc'
8 activesupport/lib/active_support/core_ext/object/metaclass.rb
@@ -0,0 +1,8 @@
+class Object
+ # Get object's meta (ghost, eigenclass, singleton) class
+ def metaclass
+ class << self
+ self
+ end
+ end
8 activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -173,6 +173,14 @@ def test_duck_typing
assert duck.acts_like?(:time)
assert !duck.acts_like?(:date)
+ def test_metaclass
+ string = "Hello"
+ string.metaclass.instance_eval do
+ define_method(:foo) { "bar" }
+ end
+ assert_equal "bar",
+ end
class ObjectInstanceVariableTest < Test::Unit::TestCase

10 comments on commit f4f6e57


Hey.. any strong example, where I could use metaclass in a rails app?


It’s really useful when it comes to metaprogramming in Ruby.


Jay Fields has a blog post on the subject. He explains some pros and cons of this approach.


Why isn’t rails using the facets gem?

Ruby on Rails member

Why isn’t facets using activesupport? :)

Ruby on Rails member

@anildigital: I’ve you’ve never felt you needed it, you probably don’t :)


I wanted to be a bit more helpful above but I was posting from my iPhone. why the lucky stiff has a great post about metaclasses here. The metaclass method is a great help for handling per-object things in your app. It can be over-used, but it can also help you do fun things like this.


Actually, the example I posted is just a convoluted example of something that can be done a million other ways. The good thing is that once you get a handle on the notion of metaclasses and such, you’ll know when and when not to use it. :)


glad this has finally been folded in so everyone does have to define this method themself


I liked this snippet best the first time I saw it….. when it was on the back of _why’s Ruby Kaigi 2007 t-shirt. or in metaid.rb

Please sign in to comment.