Generic-user-small Bharat Ruparel 29 posts

David,
I am maintaining a Rails App that is using backgroundDrb. It creates a helper file called dbrb_test_helper.rb in the test directory. Amongst other things, it has the following piece of code that I cannot understand:

class Object
 def self.metaclass
  class << self
   self
  end
 end
...
end

So we are adding a “class” method to the Object (class? instance?) named ‘metaclass’. So if I understand your teaching thus far: There is a ghost class created for the object ‘Object’ that has a method metaclass defined in it. So far so good, but what in the world are the following lines of code are for?

class << self
   self
end

I don’t get it. Kindly explain. This is one too many selfs for me.

Bharat

 
Dave_8_trans_small Dave Thomas Administrator 72 posts

We have examples of this in the screencast.


metaclass = class X
  class << self
     self
  end
end

simply returns the ghost class (the value of self in the inner class definition). By defining it in object, the method becomes available in all classes.

 
Generic-user-small Bharat Ruparel 29 posts

Thanks. So essentially it becomes a class method of Object (and inheriting classes) which returns the metaclass ‘class’ (or the ghost class) of type class?

Check this out!

http://github.com/rails/rails/commit/f4f6e57e8c2a446a4a600576f0caf0fb8921ba13

It seems like Rails 2.2 is embracing this stuff. I am pretty sure David already knows this, but is not telling us so as not to scare us off!

Bharat

 
Generic-user-small Bharat Ruparel 29 posts

And this is on Memoization:

http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization

Sounds familiar?

 
Generic-user-small James Whiteman 4 posts

Bharat,

If you haven’t already checked it out, Why has an excellent article on the above technique:

http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html

In conjunction with Dave’s screencasts, it’s a killer tutorial.

 
Generic-user-small Bharat Ruparel 29 posts

Thanks Jim. I am reading it now. I found the following post by Ola Bini to be particularly helpful. Before David’s screencasts, I could not really understand posts similar to these, I think I do now (at least until the next post asking for help).

http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html

Regards,

Bharat

6 posts, 3 voices