Skip to content

Instantly share code, notes, and snippets.

@scottwater
Created March 21, 2011 16:17
Show Gist options
  • Save scottwater/879712 to your computer and use it in GitHub Desktop.
Save scottwater/879712 to your computer and use it in GitHub Desktop.
def friendly_name(user)
temp_name = if user.first_name.blank? && user.last_name.blank?
user.email
elsif user.first_name.blank?
user.last_name
elsif user.last_name.blank?
user.first_name
else
"#{user.first_name} #{user.last_name}"
end
"#{temp_name}'s"
end
@subdigital
Copy link

I'd instead make the possessive part a separate method and favor early returning, like this:

return user.email if user.first_name.blank? && user.last_name.blank?
return user.last_name if user.first_name.blank?
return user.first_name if user.last_name.blank?
"#{user.first_name} #{user.last_name}"

You could probably make this better with more composition...

def full_name
   "#{first_name} #{last_name}".trim
end

def friendly_name
   return full_name unless full_name.blank?
   email
end

@chrisbaglieri
Copy link

You can boil this down into two conditional statements and then format your response. If first and last names are blank, assign temp name to email, otherwise "#{user.first_name} #{user.last_name}". To take into account nil first or last names, strip temp_name before returning ("#{temp_name.strip}'s".

@chrisbaglieri
Copy link

To piggyback on @subdigital's point, and you may have it already set up this way outside the gist, it probably belongs on your user model versus in a helper.

@scottwater
Copy link
Author

Thanks for the tips, especially on full_name. I think that will clean things up quite a bit.

@chris - I think full_name belongs on the model. But the friendly (possessive) part is just for the benefit of the user visiting the site, so it is probably better off in the helper. Although now that i write this it is used in one spot and can probably just be inlined in the view.

Thanks again for the tips.

@scottwater
Copy link
Author

@chris - nevermind, I get what you meant about them both being on the model. Bah...consider it committed. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment