Question

In the view I normally check for presence of a value like this:

<%= @user.name if @user.name.present? %>

Does it exist something shorter that understands my intention and not needing to repeat what I want to check? I'm looking for something like the following:

<%= @user.name if existent? %>

If this doesn't exist, would it be possible to construct a helper_method for this (and if so, how)?

Was it helpful?

Solution

Try @user.try(:name), this wilk return nil if @user is nil.

OTHER TIPS

If you are doing this in more than one place I would probably take @zrl3dx's suggestion and extract that into a helper.

Simply create a ruby file in app/helpers, such as user_helper.rb

module UserHelper
  def current_user
    @user.try(:name)
  end
end

Then in your view you can just use:

<%= current_user %>

That also provides a good way to give a default value. Say you wanted to say "Not logged in" when the user does not exist:

module UserHelper
  def current_user
    @user.try(:name) || "Not logged in"
  end
end

Of course it would probably be more helpful to give them a link at that point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top