If-Else Conditionals in Views

I find myself doing the following quite a lot:

<% if user %><%= user.name %><% else %>Anonymous<% end %>

I know that if I dont care about an else I can just do:

<%= user.name if user %>

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.

On Apr 8, 2006, at 3:32 PM, The B. wrote:

quite tedious.


Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

You can use ternary conditionals.

<%= user ? user.name : “Anonymous” %>

Cheers-
-Ezra

Brilliant! I didn’t even think of that! I’ve been doing it for ages in
Java/JSP. Not sure why it didn’t occur to me.

Ezra Z. wrote:

You can use ternary conditionals.

<%= user ? user.name : “Anonymous” %>

The B. wrote:

Brilliant! I didn’t even think of that! I’ve been doing it for ages in
Java/JSP. Not sure why it didn’t occur to me.

Ezra Z. wrote:

You can use ternary conditionals.

<%= user ? user.name : “Anonymous” %>

<%= user.name||“Anonymous” %>

joey__ now j`ey on IRC

Hi –

On Sun, 9 Apr 2006, joey__ wrote:

The B. wrote:

Brilliant! I didn’t even think of that! I’ve been doing it for ages in
Java/JSP. Not sure why it didn’t occur to me.

Ezra Z. wrote:

You can use ternary conditionals.

<%= user ? user.name : “Anonymous” %>

<%= user.name||“Anonymous” %>

The problem with that is that if user is undefined or nil, it will
raise an error when it tries to call user.name.

David


David A. Black ([email protected])
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

“Ruby for Rails” coming in PDF April 15, and in paper May 1!