From: "David A. Black" Date: 2005-11-29T07:50:26+09:00 Subject: Re: Question on class-declarations Hi -- On Tue, 29 Nov 2005, Kris wrote: > Yet Another Ruby Nuby (YARN) question. Isn't Ruby Nuby redundant? :-) But anyway, welcome. > I see Rails makes extensive use of class-declarations. > > For example: > > class LineItem < ActiveRecord::Base > belongs_to :product > ...... > > belongs_to is a class-declaration in the above code. Coming from a C It's not a declaration; it's a call to a method, specifically a class method of ActiveRecord::Base. (Actually, because of the way the ActiveRecord code base is engineered, it's sort of a pseudo-class-method, but I strongly advise you not to worry about that :-) For all practical purposes it's a class method.) A class method is a method defined directly on a class object. Here's a simple example: class C def C.hello puts "hi" end end C.hello # hi Note that the class method C.hello is completely unrelated to C's instance methods. In fact, you could have an instance method with the same name, with no conflict: class C def hello puts "hi from instance!" end end C.hello # hi C.new.hello # hi from instance! > family of languages I could not grasp this initially. When does this > code get executed - does it happen when the class is loaded for the > first time or every time a new instance of the class is created? It happens when the class definition itself is executed -- which will be when the file is loaded. > In this case I think the class-declaration code(belongs_to) looks at > the corresponding database table structure and injects attributes and > methods into the LineItem class. Am I right? Yes. The route to this is somewhat circuitous, but basically an association method will trigger the matching up of table names, thing_id fields, etc., and dynamically create the methods that allow the object access to the associated class. > I created the following example > > class B > def hello > print "Hello" > end > end > > class D < B > hello > def bye > print "bye" > end > end > > I tried this in irb and got an error. Why doesn't this work? In Rails I > think mixins are used to provide this kind of functionality. It doesn't work because hello and bye are both instance methods -- but by calling hello in the definition scope of D, you're treating it like a class method. You're basically saying: send the message "hello" to the class object D, which doesn't do anything because D doesn't respond to that message. > To me these seem to be idioms of the language. Is there a site where > you could find gems like these? I'm not quite sure what you mean... but I hope the above is helpful :-) David -- David A. Black dblack@wobblini.net