Forum: Ruby on Rails Re: If-Else Conditionals in Views

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Bradley M. (Guest)
on 2006-04-09 10:59
(Received via mailing list)
> I find myself doing the following quite a lot:
> <% if user %><%= %><% else %>Anonymous<% end %>
> Is there any simpler way to handle the else?  This is a simple example
> so it's not really an issue.. but for more complicated tests this gets
> quite tedious.

For me, I moved the whole thing into a helper.

Because usernames are a potential relationship that I may want to give
more information on, I created a helper that did this, parameterized
by the user object.

In the simple case, it does what you show.  In other cases it will
return a link to the user's information.  If the user is the favorite
of the current user, it may throw in a span tag so that I can colour
the link differently, or include a small inline image.

In my view, I'll have something like:
  <%= render_username %>

Keeps the view clean, and still provides the flexibility I want, plus
it keeps things nice and DRY.

Bradley M.
This topic is locked and can not be replied to.