Hi --

On Mon, 24 Nov 2008, Matthew Madson wrote:

> Can anyone explain exactly what happens when the interpreter interprets
> attr_reader and its kin?
>
> E.G. where is the method located (in which module, class) and what does
> it do with the symbols in order to expand the method call into an
> instance method of the calling class object?

attr_reader and friends are private instance methods of the class
Module:

>> Module.private_instance_methods(false).grep(/attr/)
=> ["attr_accessor", "attr_writer", "attr_reader", "attr"]

which means that as long as self is an instance of Module or one of
its subclasses, those methods can be called. The Class class is a
subclass of Module, so instances of Class can execute those methods
too. That's what's happening when you do:

   class C
     attr_accessor :x
   end

As for what it does: see Greg's Ruby implementation, and also the
original C code which is in eval.c (look for the definition of
rb_attr). It basically calls rb_define_method, which is a general
method for adding methods to classes.

I used implementing attr_* as a metaprogramming exercise in a Ruby
course I taught last week, and it was very instructive. Amazing what
you can do in Ruby, without even getting terribly convoluted or
opaque.


David

-- 
Rails training from David A. Black and Ruby Power and Light:
   Intro to Ruby on Rails  January 12-15   Fort Lauderdale, FL
   Advancing with Rails    January 19-22   Fort Lauderdale, FL *
   * Co-taught with Patrick Ewing!
See http://www.rubypal.com for details and updates!