Yet Another request to help DRY some code

The essential element I’m missing (I think), is some sort of hook to
help me iterate through all of my model’s to_one relationships.

My model has lots of them, but for a given object only 1 matters. So
“att_value” is supposed to represent whichever one it is that matters.
(and the one that matters is determined by another attribute called
class_name)

class PageAttribute < ActiveRecord::Base

belongs_to :page

has_one :boolean_page_attribute, :class_name =>
‘BooleanPageAttribute’, :dependent => :destroy
has_one :date_page_attribute, :class_name => ‘DatePageAttribute’,
:dependent => :destroy
has_one :string_page_attribute, :class_name => ‘StringPageAttribute’,
:dependent => :destroy
has_one :page_link_page_attribute, :class_name =>
‘PageLinkPageAttribute’, :dependent => :destroy
has_one :uploaded_file_page_attribute, :class_name =>
‘UploadedFilePageAttribute’, :dependent => :destroy

def att_value
if(self.class_name.to_s == ‘BooleanPageAttribute’)
return self.boolean_page_attribute
end
if(self.class_name.to_s == ‘DatePageAttribute’)
return self.date_page_attribute
end
if(self.class_name.to_s == ‘StringPageAttribute’)
logger.debug “returning string_page_attribute” +
string_page_attribute.to_s
return self.string_page_attribute
end
if(self.class_name.to_s == ‘PageLinkPageAttribute’)
return self.page_link_page_attribute
end
if(self.class_name.to_s == ‘UploadedFilePageAttribute’)
return self.uploaded_file_page_attribute
end
end

def att_value=(val)
if(self.class_name.to_s == ‘BooleanPageAttribute’)
if val.is_a? Hash
self.boolean_page_attribute.attributes = val
else
self.boolean_page_attribute = val
end
end
if(self.class_name.to_s == ‘DatePageAttribute’)
if val.is_a? Hash
self.date_page_attribute.attributes = val
else
self.date_page_attribute = val
end
end
if(self.class_name.to_s == ‘StringPageAttribute’)
if val.is_a? Hash
self.string_page_attribute.attributes = val
else
self.string_page_attribute = val
end
end
if(self.class_name.to_s == ‘PageLinkPageAttribute’)
if val.is_a? Hash
self.page_link_page_attribute.attributes = val
else
self.page_link_page_attribute = val
end
end
if(self.class_name.to_s == ‘UploadedFilePageAttribute’)
if val.is_a? Hash
self.uploaded_file_page_attribute.attributes = val
else
self.uploaded_file_page_attribute = val
end
end
end

…etc…

end

thanks,
Jacob

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs