From: ptkwt@... (Phil Tomson) Date: 2005-11-23T18:47:26+09:00 Subject: Re: pattern: auto-running module init code In article <3736dd30511230027i2d31677aw4f36c01d289636f0@mail.gmail.com>, Sean O'Halpin wrote: >Hi Phil, > >You can also use super: > >class Bar > def initialize(*args, &block) > puts "in Bar" > super > end >end > >class Foo < Bar > def initialize(*args, &block) > puts "in Foo" > super > end >end > >f =3D Foo.new > >module Mod > def initialize(*args, &block) > puts "in Mod" > super > end >end > >class Foo > include Mod >end > >f =3D Foo.new Ah, that would be too simple ;-) And the user of the module has to remember to call 'super' somewhere in the constructor, I was trying for something more automatic :) Hmmm...This brings up another thought: Just like C++ programmers are often advised to go ahead and make their methods virtual in case someone comes along and subclasses, should we be generally calling super in our constructors in case someone comes along and mixes-in a module with an 'initialize' method defined? > >--- OUTPUT --- >in Foo >in Bar # after the 2nd f.new: >in Foo >in Mod >in Bar > >or Module.included > >class Bar > def initialize(*args, &block) > puts "in Bar" > super > end >end > >class Foo < Bar > def initialize(*args, &block) > puts "in Foo" > super > end >end > >module Mod > def self.included(obj) > puts "in Mod" > end >end Perhaps, but isn't 'obj' in this case actually the including class? to make it more clear, change to: module Mod def self.included(obj) pus "in Mod: obj is: #{obj} #{obj.class}" end end > >class Foo > include Mod >end > Then the output will be: in Mod: obj is: Foo Class and it is called even before there is any instance of Foo created. So any initialization code you want to run by using 'included' will be class-level initialization, not instance-level. That may or may not be what you want. Phil