views:

89

answers:

4

Is there any way in a Rails STI situation to throw an error when the base class is Instantiated? Overriding initialize will do it but then that gets trickled down to the subclasses.

Thanks

A: 

In the initialize function check that the class is the STI base class.

Though the question is why would you exactly want to do this? It seems more likely that trying out a different design might help you more.

Jakub Hampl
+3  A: 

You can do self.abstract_class = true in the base class to tell ActiveRecord that it's an abstract class.

John Topley
+1  A: 

You can try this:

class BaseClass
  def initialize
    raise "BaseClass cannot be initialized" if self.class == BaseClass
  end
end

class ChildClass
end

the result will be:

a = BaseClass.new  # Runtime Error
b = ChildClass.new # Ok

Hope that helps

SamChandra