ruby-on-railsrubyruby-on-rails-4helpermethods

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


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


Solution

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