From time to time I get stumped - I just can't find a *good* name for a class, method or variable. Sometimes I search for synonyms online or ask a colleague for suggestions. However, the naming conventions used in rails makes things easier, yet they may not scale very well.
For example, a polymorphic comment association is usually named commentable, whereas for an image - imageable. Simple enough, but the fact is that I actually ended up with names such as photoable, wallable and wizzardable (I kid you not).
Right now I'm using parent, and it works great.
belongs_to :parent, :polymorphic => true
However, parent.parent.post is not as informative as imageable.commentable.post, but frankly this is hardly a problem. Based on
this railscasts episode, I could get the current parent inside a controller by using the following:
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
Do this for images as well, and you'll probably see a pattern. So how about we just rewrite it in the application controller:
def current_parent
return @current_parent if @current_parent
params.each do |name, value|
if name =~ /(\w+)_id$/
@current_parent = $1.classify.constantize.find(value)
return @current_parent
end
end
nil
end
So using parent actually makes sense.
If your application gets large enough, or you need to fix a bug on an older project you'll probably notice one thing - you can't recall the column names. Was it name, subject, title or content, contents, description? This gets even worse if you haven't wrote that code in the first place. For more than a year, on the projects I've been working on (which have been quite a few) I decided on always sticking with name for single line descriptions (varchar) and contents for the ones with multiple lines (text). There may be other fields of course, but this worked out surprisingly well.
It feels nice when a colleague writes the frontend and doesn't even need to look over the database schema.