Forum: Ruby on Rails If-Else Conditionals in Views

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
29d82d169c6037d4cbafce0b20fcf04e?d=identicon&s=25 The Barge (Guest)
on 2006-04-09 00:32
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.
6076c22b65b36f5d75c30bdcfb2fda85?d=identicon&s=25 Ezra Zygmuntowicz (Guest)
on 2006-04-09 00:46
(Received via mailing list)
On Apr 8, 2006, at 3:32 PM, The Barge wrote:

> quite tedious.
>
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails

	You can use ternary conditionals.

<%= user ? user.name : "Anonymous" %>

Cheers-
-Ezra
29d82d169c6037d4cbafce0b20fcf04e?d=identicon&s=25 The Barge (Guest)
on 2006-04-09 01:09
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 Zygmuntowicz wrote:
> 	You can use ternary conditionals.
>
> <%= user ? user.name : "Anonymous" %>
6dab365a82517fb694650a57ee88e4a4?d=identicon&s=25 joey__ (Guest)
on 2006-04-09 02:37
The Barge 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 Zygmuntowicz wrote:
>> 	You can use ternary conditionals.
>>
>> <%= user ? user.name : "Anonymous" %>

<%= user.name||"Anonymous" %>

joey__ now j`ey on IRC
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-04-09 03:08
(Received via mailing list)
Hi --

On Sun, 9 Apr 2006, joey__ wrote:

> The Barge 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 Zygmuntowicz 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 (dblack@wobblini.net)
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
This topic is locked and can not be replied to.