Tuesday, April 8th, 2008...3:24 pm
Clean Up Your Code By Overwriting Methods
Just wanted to share a quick Rails tip that has come in useful for me in the past. Let’s say you’re creating a forum, and when users register, they create a username (like “kyleslat”). However, they can edit their profile and add their full name (like “Kyle Slattery”). They also can decide what they want to have displayed on their posts (like “Kyle S.”). All of these are fields in the database (username, full_name, and display_name, respectively). Now, when writing your templates, you have to make sure you display the correct name. If you use if-statements, this could be really messy:
<%=
if @user.display_name
@user.display_name
elsif @user.full_name
@user.full_name
else
@user.username
end
%>
Luckily, Ruby has a nice syntax that can compress that into the following:
<%= @user.display_name || @user.full_name || @user.username %>
However, you’ll likely want to display this in many different places on your forum, and what if you want to change the logic? That means a lot of code to change, and it’s really likely you’ll miss somewhere. But, what if you could just call @user.display_name, and it gave back the right name? Thanks to the ability to overwrite methods, this is really simple to do. Just do the following in your User model:
class User < ActiveRecord::Base
def display_name
super || full_name || username
end
end
Now, if you want to change what displays for a user’s name, you only have to change it in one place, rather than throughout your code.
Leave a Reply