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)
else
  Referral.create(:user => current_user,
                  :referer => referer,
                  :team => Team.find(session[:team_id]))
end

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]
  end
  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?

Jared Carroll

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.