From: Trans Date: 2007-03-15T23:21:52+09:00 Subject: Re: General Ruby OOP Question - using inheritance or include for shared attributes On Mar 15, 4:25 am, "John Wilger" wrote: > On Mar 15, 12:11 am, "Trans" wrote: > > > > > On Mar 15, 1:35 am, james.d.mast...@gmail.com wrote: > > > I have a generic Ruby OOP question. Which is the more "correct" way > > > to share methods between two similar classes that do not necessarily > > > need to inherit from anything else: inheritance or include (as a mix- > > > in)? > > > When it comes to Ruby there is a huge consideration here: Do you or > > will you ever wish to pass on class level methods? Or more technically > > speaking, do you want class singleton methods to be in the inheritance > > chain? If so then you have to use a class, since modules don't allow > > it (to my eternal dismay). For example: > > > class X; def self.x; "x"; end; end > > class Y < X; end > > Y.x #=> x > > > module X; def self.x; "x"; end; end > > class Y; include X; end > > Y.x #=> error > > Modules may not allow it directly, but it seems that you can work > around it easily enough: > > module A > def self.included( other ) > def other.foo > puts 'bar' > end > end > end > > class B > include A > end > > class C < B > end > > #> B.foo > #=> bar > # > #> C.foo > #=> bar > > Or am I missing something important here? Sure. You can do all sorts of tricks to get the desired behavior. The point is simply "it ain't natural". I don't really hold a theoretical view of classes and modules. I work with this on strictly practical level. A simple example is ActiveSupport's mattr methods. I haven't looked at them in a while so maybe they've _hacked_ a solution since then, but if you use mattr in a module it'll break if included in a class or other module. > Really, the choice of whether to use inheritance or module inclusion > comes down to the question of whether you are sharing identity or just > behavior. For instance, do you want: There's a duck around here that doesn't know the difference ;-) T.