Safe nil in rails views

If you know grails, there is a feature like this: <% user.name? %>
that prevents to chek if the value is null or not.
In rails view I have to do
<% if user.name %>
<%= user.name %>
<% end %>
to display user.name if it is not nil.
There is a shortcut or some feature like that in grails?

user.presence || “”

see http://rubydoc.info/docs/rails/3.0.0/Object:presence

And if user can potentially be nil, you can also use

user.try(:presence) || “”

This will avoid “undefined method ‘presence’ for nil:NilClass” errors.

On 10 Sep 2010, at 10:27, Christiaan Van den Poel wrote:

<% end %>
to display user.name if it is not nil.
There is a shortcut or some feature like that in grails?

Best regards

Peter De Berdt

Msan M. wrote:

If you know grails, there is a feature like this: <% user.name? %>
that prevents to chek if the value is null or not.
In rails view I have to do
<% if user.name %>
<%= user.name %>
<% end %>
to display user.name if it is not nil.
There is a shortcut or some feature like that in grails?

<% if user && user.name %>

On 10 September 2010 09:25, Mauro [email protected] wrote:

If you know grails, there is a feature like this: <% user.name? %>
that prevents to chek if the value is null or not.
In rails view I have to do
<% if user.name %>
<%= user.name %>
<% end %>
to display user.name if it is not nil.
There is a shortcut or some feature like that in grails?

<%= user.name if user.name %> may be the most concise, or
<%= user.name if user && user.name %> if user may be nil

Colin

On 10 September 2010 09:25, Mauro [email protected] wrote:

If you know grails, there is a feature like this: <% user.name? %>
that prevents to chek if the value is null or not.
In rails view I have to do
<% if user.name %>
<%= user.name %>
<% end %>
to display user.name if it is not nil.

Not a general solution I know, but in such a situation I supply a
method of User, display_name, that returns the name or empty string
(or “Unknown” possibly, dependent on requirement).

Colin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs