[rspec-users] newbie cucumber tutorial

Matt Wynne matt at mattwynne.net
Wed Dec 24 04:32:12 EST 2008


On 24 Dec 2008, at 02:26, Sarah Allen wrote:

> Matt Wynne wrote:
>> ActiveRecord::Validations uses a trick that's used widely in rails,
>> and is arguably[1] becoming a Ruby idiom, apparently.
>>
>> This is the interesting bit, around line #275:
>>
>>     def self.included(base) # :nodoc:
>>       base.extend ClassMethods
>>
>> So basically that means that when the class ActiveRecord::Base
>> includes the module ActiveRecord::Validations, that module extends  
>> the
>> thing which included it (in this case ActiveRecord::Base) with the
>> class methods defined in ActiveRecords::Validations::ClassMethods.
>>
>> Does that make sense?
>
> um, no.  You say that the class ActiveRecord::Base includes the module
> ActiveRecord::Validations, but I don't see that in the code I'm  
> looking
> at here:
> http://dev.rubyonrails.org/browser/branches/2-0-stable/activerecord/lib/active_record/base.rb

You almost got it. Try here instead:
http://dev.rubyonrails.org/browser/branches/2-0-stable/activerecord/lib/active_record.rb

> If I assume that I'm looking at the wrong code or it happens thru some
> magic then you can make a module which will add its class methods to  
> the
> class which includes it?

Yes, that's basically what the self.included trick does. As I say,  
it's debatable whether this is a neat trick or a horrible hack. If you  
were reading the code that included the module,. might have only  
expected that would add instance methods, rather than class methods as  
well.

> Is that some kind of trick to create multiple
> inheritance?

Not really in that particular case. Ruby modules generally allow you  
to do multiple inheritance by 'mixing in' behaviour to classes, but  
that would be when you use 'include' to bring the methods defined in  
the module into the class itself.

> Is there any way without digging thru source to know which
> class include methods from other classes or do y'all just get so cozy
> with every Rails class you use that you "just know?"

If you have hold of a class in ruby, there are ways to ask it what  
modules / classes it inherits from, but I can't remember them off the  
top of my head, sorry. Try messing around in irb for this kind of thing.

Matt Wynne
http://blog.mattwynne.net
http://www.songkick.com



More information about the rspec-users mailing list