If-Else Conditionals in Views


#1

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.


#2

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

quite tedious.


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


Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

You can use ternary conditionals.

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

Cheers-
-Ezra


#3

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” %>


#4

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


#5

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 (removed_email_address@domain.invalid)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

“Ruby for Rails” coming in PDF April 15, and in paper May 1!
http://www.manning.com/black