I’ve got an abstract model that has a lot of implementing submodels. I’d like to be able to define some functions in the abstract model that rely on the submodel’s own definitions when called on the submodel. Is such a thing possible in Ruby on Rails?
Example, where the length attributes are defined in the submodels:
class Animal
validates_inclusion_of :length, :in => MIN_LENGTH..MAX_LENGTH
end
class Elephant < Animal
MIN_LENGTH = 5
MAX_LENGTH = 20
end
Then when I go to Elephant.new.save! I’d like it to run the validation with Elephant’s constants.
The reason I want to do this is because the fact that there will be such validations is going to be universal to all of the submodels, the only thing that varies is the value of the constants.
When I tried to do it like this, or with lower-cased methods, in both cases I get a name error for the undefined values.
Is such a thing possible in Rails?
gets executed when Ruby sees your Animal class. So, it’s naturally it uses the values of
MIN/MAX_LENGTHas they appear at that time. To override this behavior you can do this:Then define in both your
AnimalandElephantclasses (or just in the last one if you don’t plan to “gave birth” to a “justAnimal“):This way your range for
:inwill be calculated when it is needed, providing:inwith a suitable range for some species.P.S. I guess you omitted the base class for your
Animaljust to save few keystrokes 😉