CodeOverload
CodeOverload

Reputation: 48495

Shorter way of doing x.present? ? x : z

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

Answers (2)

Marcelo De Polli
Marcelo De Polli

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

SciPhi
SciPhi

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

Related Questions