0

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

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

2 Answers2

1

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

zrl3dx
  • 7,699
  • 3
  • 25
  • 35
0

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.

csexton
  • 24,061
  • 15
  • 54
  • 57
  • Thanks a lot, but I was looking for a more general solution, to validate presence of any instance variable or attribute. – Fellow Stranger Jan 06 '14 at 02:34
  • In that case, have you considered something like a [Null Object](http://robots.thoughtbot.com/rails-refactoring-example-introduce-null-object)? – csexton Jan 06 '14 at 02:51