From: Joel VanderWerf Date: 2006-05-28T11:53:27+09:00 Subject: Re: modularizing class methods [LONG] transfire@gmail.com wrote: > Interesting approach. It's a little bit of a misnomer mind you, becasue > you have taken over the include processes such that you are not > actually including module definitions, but rather are defining code in > the base class itself. In other words, while your class will report > ancestors of NameFields and AddressFields, there are actually no > methods defined in those modules. True, but the parallel with the following is just so appealing, that I thought #include was the best mechanism to use: module NameFields attr_accessor :first, :last, :middle end module AddressFields attr_accessor :street, :city, :state, :zip end class Person include NameFields include AddressFields end (The above depends on the fact that attrs are stored by name, and not incrementally allocated in some linear store.) Anyway, you *might* want to put some definitions in the modules, and have them propagate to the class via include, like this (in the context of my example from the previous post): module AddressFields extend ModuleMethodSaver field :street, :city, :state, :zip def postal_address [street, city, "#{state} #{zip}"].join("\n") end end Using include is the most natural way to do this. > I have seen another common way of doing this: > > module NameFields > def included( base ) > base.class_eval %{ > field :first, :last, :middle > } > end > end Yep, same effect, but a little harder to write naturally. Also, you cannot copy and paste from the class def to the module def, as you can with ModuleMethodSaver: class Person < ArrayWithNamedFields field :first, :last, :middle end is the same as module NameFields extend ModuleMethodSaver field :first, :last, :middle end class Person < ArrayWithNamedFields include NameFields end So it makes refactoring easier. (Well, ok, you still have to type the "extend" line. But that's easier to remember than the def included(... stuff.) Thanks for the comments! -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407