extra action

Jared Carroll

The following code samples, taken from a controller, demonstrate different ways of creating a Referral with or without a Team. A Referral represents one user inviting another eventual user to the site and optionally to their Team. Whether this is the best way to model this doesn’t matter, right now, I just want to take a look at a couple different code samples.

if session[:team_id].blank?
  Referral.create(:user => current_user,
                  :referer => referer)
  Referral.create(:user => current_user,
                  :referer => referer,
                  :team => Team.find(session[:team_id]))

Very straightforward, nothing special there. Here’s another version:

Referral.create(:user => current_user,
                :referer => referer,
                :team => Team.find_by_id(session[:team_id]))

Much more succinct by relying on the #find_by_id hack. I really don’t like that #find_by_id. To me it’s lazy coding along the lines of this:

<%= h user.address.street rescue '' %>

instead of putting a conditional:

<% unless user.address.nil? %>

<%= h user.address.street %>
<% end %>

Nobody likes conditional logic but come on.

Ok, let’s look at another version.

  unless session[:team_id].blank?
    team = Team.find session[:team_id]
  Referral.create(:user => current_user,
                  :referer => referer,
                  :team => team)

Now you might think that’s not going to work when that condition is true, but through some crazy hack in Ruby it does not raise an error. I didn’t realize about that until recently, not sure how commonly known it is. And for that reason I’m going to have to outlaw this version as being way too tricky.

What do you guys think?