From: Brian Marick Date: 2007-12-13T11:49:41+09:00 Subject: Re: Abstract -- what's the Ruby way? > On Dec 12, 5:10 pm, "Tim Rowe" wrote: >> What's the Ruby way to define a class that shouldn't be >> instantiated, but >> with descendants that can be? Other than a comment in the >> documentation, of >> course. >> I missed the beginning, so hope this response is to the point. See the code below. (What I do is name the class AbstractSomething and trust that's warning enough.) ================================= class Abstract attr_reader :abstract_class_initialize_args def initialize(*args) raise "Initialized abstract class #{self.class}" if self.class == Abstract @abstract_class_initialize_args = args end end class SubclassWithInitializer < Abstract attr_reader :subclass_initialize_arg def initialize(arg) super @subclass_initialize_arg = arg end end class SubclassWithoutInitializer < Abstract end require 'test/unit' class TestCase < Test::Unit::TestCase def test_abstract_class_raises_exception assert_raises(RuntimeError) { Abstract.new } end def test_a_subclass_can_call_super sub = SubclassWithInitializer.new('arg') assert_equal(['arg'], sub.abstract_class_initialize_args) assert_equal('arg', sub.subclass_initialize_arg) end def test_a_subclass_need_not_define_its_own_initialize sub = SubclassWithoutInitializer.new('arg') assert_equal(['arg'], sub.abstract_class_initialize_args) end end ----- Brian Marick, independent consultant Mostly on agile methods with a testing slant www.exampler.com, www.exampler.com/blog, www.twitter.com/marick