I'm trying to figure out the best practice for this. It should be relatively straight-forward, but I'm not sure.
We have a few models that have some similar attributes, for example: name
, description
, image
. However, for semantic reasons or otherwise, some of those attributes aren't 100% matching:
a Video
model might have a title
instead of a name
, and an Article
model might not have a description
but rather have content
.
We do however want to present those models in a view consistently in terms of layout. For example, we want to generate a list of items. Each item shows: a thumbnail on the left, name (or title) as a header, description (or truncated content) below. The thumbnail will link to the object page etc.
Now to the question:
How can we 'duck type' those objects for the view with minimal if
or case
clauses? Ideally we'll define some kind of an interface / module and apply it to each model so when we call <something>.description
it knows how to fetch it for each object (either call description
directly, or content
etc)
Is there a standard / recommended way to do this in ruby / rails?
I would create aliases in each model for the generic name. For example, if you want to always call the description
method in your view, just add an alias for the attribute:
class Article < ActiveRecord::Base
alias_attribute :description, :content
end
This will keep logic out of your views entirely and allow you to talk to your database object through a consistent interface.