I'm working on an application that includes single table inheritance classes.
Here is the structure that I am working on:
Classes
---------------------
Asset (parent class)
Acreage (child class of Asset)
Crop (child class of Asset)
Relationships
---------------------
Crop belongs_to Acreage
An Acreage is a physical piece of property that has a size (acres), gps coordinates, physical address, etc.
A Crop is something that is planted in an Acreage for a season.
A Crop also has a size (acres), gps coordintes, physical address, etc and can generally pull that information from Acreage. On occasion there may be more than one crop planted in an Acreage (the Acreage is split up). In this case, each Crop object must override the Acreage values with values of its own.
In my crop.rb model, I set up the attribute definitions as follows:
Code:
def acres
if self.id.nil? #does a crop object even exist?
return #if not, quit
elsif super.nil? #does the crop object have override values defined?
Acreage.find_by_id(self.acreage_id).acres #if not, get values from acreage
else
super #else display override values defined in the crop object
end
end
def latitude
if self.id.nil?
return
elsif super.nil?
Acreage.find_by_id(self.acreage_id).latitude
else
super
end
end
def longitude
if self.id.nil?
return
elsif super.nil?
Acreage.find_by_id(self.acreage_id).longitude
else
super
end
end
But I can see that I am repeating myself in each method to check for existence of the object and whether the object should get its values from acreage or from itself. Can anyone point me in the right direction for cleaning up the repetition?
Thanks,
Raklet