Standalone helper_method checking for presence, e.g. @user.name if existent?

64 views Asked by At

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)?

2

There are 2 answers

0
zrl3dx On BEST ANSWER

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

2
csexton On

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.