3

I have this code:

<div class="alert alert-success">
  <a href="#" class="alert-link"><%= notice %></a>
</div>

I need to put an if statement around it to only show the entire div if notice isn't nil. I've tried a couple of ways but can't get the syntax right.

Carla Dessi
  • 9,086
  • 9
  • 39
  • 53

2 Answers2

9

You have to use nil? method of the Object class of ruby

<% unless notice.nil? %>
  <div class="alert alert-success">
    <a href="#" class="alert-link"><%= notice %></a>
  </div>
<% end %>

Above code show the entire div if notice isn't nil.

I'll also recommend you to read difference between nil, blank? & present

Community
  • 1
  • 1
Salil
  • 46,566
  • 21
  • 122
  • 156
  • 1
    Replacing first line with `<% if notice.present? %>` would also check for `false` or "blank" objecte, e.g. empty strings. – Marek Lipka Aug 30 '13 at 09:49
  • @MarekLipka present? also return false false for `''`, `' '`, `nil`, `false` amd question says `I need to put an if statement around it to only show the entire div if notice isn't nil` – Salil Aug 30 '13 at 09:55
  • `false` for `nil` isn't "false". And that's why I put it on comment instead of separate answer, as some kind of suggestion to question Author. – Marek Lipka Aug 30 '13 at 09:57
  • `1.9.3-p327 :024 > false.nil? => false ` – Salil Aug 30 '13 at 10:01
  • That's not what I meant. I mean `nil.present? # => false` and that's correct `false`, not "false" `false` like you wrote in comment. – Marek Lipka Aug 30 '13 at 10:02
  • Yeah i got it @MarekLipka what you want to say, even i used `blank?`, `present?` methods only instead of `nil?`. But, as she want to hide div only when `notice` is `nil` i write `unless notice.nil?` instead of `if nil.present?` – Salil Aug 30 '13 at 10:06
  • 1
    You are right, of course, usage of `nil` meets perfectly question criteria as they are expressed. – Marek Lipka Aug 30 '13 at 10:11
2

All given ansers are correct, altough I prefer this one using rails presence check:

<% if notice.present? %>
  <div class="alert alert-success">
    <a href="#" class="alert-link"><%= notice %></a>
  </div>
<% end %>

It is a detail, but is more robust since this condition will correctly evaluate to false when using empty string (or empty array, if you might be using multiple notices in the future).

And it reads flawlessly, doesn't it :)

jurglic
  • 3,599
  • 1
  • 17
  • 13