Reputation: 48495
This is really starting to look repetitive and bulky when I do something like:
Name: <%= @user.name.present? ? @user.name : "Unknown" %>
I know I can do @user.name || "Unknown"
but that doesn't handle empty strings as far as i know.
Is there a shorter approach?
Upvotes: 2
Views: 70
Reputation: 29291
<%= @user.name.presence || "Unknown" %>
From the Rails official documentation:
presence()
Returns object if it’s present? otherwise returns nil. object.presence is equivalent to object.present? ? object : nil.
http://api.rubyonrails.org/classes/Object.html#method-i-presence
Upvotes: 6
Reputation: 2665
You could add a helper method
def view_name( user, default="Unknown" )
user.name.present? ? @user.name : default
end
so that your view is just :
Name: <%= view_name( @user ) %>
Upvotes: 0