From: Paul Brannan Date: 2001-11-21T23:45:33+09:00 Subject: [ruby-talk:26027] Re: Redefining new? On Wed, 21 Nov 2001, Michael Sullivan wrote: > I'm looking to have some sort of initialization done when the class is > created so the person using my class doesn't have to bother with calling > "super" or anything like that. I know how programmers can get sloppy > when they are forced to include non-standard constructs beyond what is When the base class (or mixin) can be default constructed, it would certainly be nice to be able to not have to call super, but on the other hand, it doesn't allow me the option of shooting myself in the foot. As someone pointed out, Ruby programmers are used to using super; if they aren't, then they probably shouldn't be using inheritance. However, even a good programmer can make mistakes, and it's always nice to be able to have the compiler or interpreter warn you when you are doing something that might be unwise. In C++, I get an error if I try to write a constructor that does not explicitly call a base class's constructor, if the base class cannot be default constructed. For example, class Foo { public: Foo(int); }; class Bar : public Foo { public: Bar() {} }; when compiled with g++, gives me: foo.cpp: In method `Bar::Bar()': foo.cpp:8: no matching function for call to `Foo::Foo ()' foo.cpp:3: candidates are: Foo::Foo(int) foo.cpp:4: Foo::Foo(const Foo &) It would be nice to have a similar feature in Ruby: class Foo def initialize(x) @x = x end end class Bar < Foo def initialize(y) @y = y end end Bar.new This should probably emit a warning, since the base class is now left uninitialized. If this is the desired effect, then it should be possible to explicitly allow the base class to be left uninitialized: class Bar < Foo def initialize(y) @y = y nosuper # just a thought; this could be called anything end end > What would be really ideal is if there were code in a module that could > be executed when the module is included in a class, or when the first > instance of the class is created. Look at append_features. I've used it before to raise an exception if a module is mixed in to a class that does not have the required interface: http://rm-f.net/~cout/ruby/treasures/RubyTreasures-0.1/lib/hacks/safe_mixin.rb.html Paul