From: Ryan Leavengood Date: 2005-11-29T07:53:19+09:00 Subject: Re: Question on class-declarations On 11/28/05, Kris wrote: > Yet Another Ruby Nuby (YARN) question. > > 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 > 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 will help if you think about class definitions as being as much executable code as the rest of your script. Then think about in what context code within a class definition is executed. For example: irb(main):001:0> class C irb(main):002:1> p self irb(main):003:1> p self.class.name irb(main):004:1> def foo irb(main):005:2> p self irb(main):006:2> p self.class.name irb(main):007:2> end irb(main):008:1> end C "Class" => nil irb(main):009:0> C.new.foo # "C" => nil As you can see the code that prints out self and self.class.name within the class is executed when the class is created, and the context of the code is the class itself. Then when you run the instance method the context is an instance of the class. So given this, where do you think the method belongs_to is defined? When it is called, self is the class itself, which is an instance of Class, so the methods much be instance methods of Class: irb(main):010:0> class Class irb(main):011:1> def print_this(symbol) irb(main):012:2> p symbol irb(main):013:2> end irb(main):014:1> end => nil irb(main):015:0> class C irb(main):016:1> print_this :sym irb(main):017:1> end :sym => nil > 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 you've got the idea here. > I created the following example > > class B > def hello > print "Hello" > end > end > > class D < B > hello > def bye > print "bye" > end > end The problem is you need to define an instance method of the class Class, not of a super class. > 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. > > To me these seem to be idioms of the language. Is there a site where > you could find gems like these? Check this out: http://www.rubygarden.org/ruby?RubyIdioms Ryan