public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Added Object#metaclass
josh (author)
Tue Jul 15 19:24:00 -0700 2008
commit  f4f6e57e8c2a446a4a600576f0caf0fb8921ba13
tree    e3541a545c85cc00a5182532b4c2b6d9376c815d
parent  89eec91e670ae267cd88b2b3555bfefe527f0eaa
...
1
2
3
 
4
...
1
2
3
4
5
0
@@ -1,4 +1,5 @@
0
 require 'active_support/core_ext/object/conversions'
0
 require 'active_support/core_ext/object/extending'
0
 require 'active_support/core_ext/object/instance_variables'
0
+require 'active_support/core_ext/object/metaclass'
0
 require 'active_support/core_ext/object/misc'
...
173
174
175
 
 
 
 
 
 
 
 
176
177
178
...
173
174
175
176
177
178
179
180
181
182
183
184
185
186
0
@@ -173,6 +173,14 @@ class ObjectTests < Test::Unit::TestCase
0
     assert duck.acts_like?(:time)
0
     assert !duck.acts_like?(:date)
0
   end
0
+
0
+  def test_metaclass
0
+    string = "Hello"
0
+    string.metaclass.instance_eval do
0
+      define_method(:foo) { "bar" }
0
+    end
0
+    assert_equal "bar", string.foo
0
+  end
0
 end
0
 
0
 class ObjectInstanceVariableTest < Test::Unit::TestCase

Comments

anildigital Sun Jul 20 05:32:08 -0700 2008

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

nakajima Sun Jul 20 07:06:14 -0700 2008

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

ryanb Sun Jul 20 08:12:17 -0700 2008

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

smtlaissezfaire Sun Jul 20 10:08:17 -0700 2008

Why isn’t rails using the facets gem?

josh Sun Jul 20 11:17:20 -0700 2008

Why isn’t facets using activesupport? :)

NZKoz Sun Jul 20 11:50:16 -0700 2008

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

nakajima Sun Jul 20 12:00:48 -0700 2008

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.

nakajima Sun Jul 20 12:02:02 -0700 2008

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. :)

cpjolicoeur Mon Jul 21 17:40:06 -0700 2008

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

hoverbird Fri Jul 25 17:05:03 -0700 2008

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