I have 3 classes ("Truck", "Semi", "Motorcycle") that all inherit from
the "Vehicle" class.
Each subclass has an attribute for "Wheels" that tells how many wheels
the vehicle has (I do not store these values in the database because
they will never change)
I'm wondering what is the preferred method for handling this? Right now
I have individual methods in each class for "Wheels":
Maybe you have a particular limited set of vehicles but trucks I know have from 4 to 10 (or more) wheels and motorcycles have 2 or 3 wheels and Semi-trailer trucks have 10 to 20 (or more) wheels depending on application. I would store the number of wheels in the database.
I agree with Norm that this feels inauthentic - objects are typically
used to 'model' real world things and relationships, and I can see
lots of exceptions on your horizon
In any case, I would probably do something like:
class Vehicle
attr_accessor :wheel_count
end
class Truck < Vehicle
def initialize(wheel_count = 4)
@wheel_count = wheel_count
end
end
... and so on.
I'd also recommend 'Practical Object-Oriented Design in Ruby'
( http://www.poodr.info/ ) for some good thoughts on this.
I originally tried to set it up that way and it works until I retrieve a
record from the database. I dont think it triggers the initialize
function. because I cant call the "wheels" method on an object after I
retrieve it.
What you suggested would work. My approach would be to have a vehicle class/table with the characteristics of the vehicle types just because I think STI is more bother than reward unless there are other things that you do not mention that would drive you in that direction. I prefer the simplest approach that will do what is needed. It makes it easier to pass it on to someone else and I am not as likely to forget why things are like they are.
Sorry, my bad for not explicitly saying that the approach above does
imply you're going to persist that attribute (which makes sense if the
value is variable).