0

I'm currently looking at a piece of code from the excellent Rails-composer and I don't understand what the Embedded Ruby in the 3rd line does:

<% flash.each do |name, msg| %>
  <% if msg.is_a?(String) %>
    <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
      <a class="close" data-dismiss="alert">&#215;</a>
      <%= content_tag :div, msg, :id => "flash_#{name}" %>
    </div>
  <% end %>
<% end %>

I've looked at the Ruby documentation with no luck so far. Once I understand how this code works I'd like to extend it to support all levels of flash[] messages.

Andrew Marshall
  • 89,426
  • 20
  • 208
  • 208
Francis Ouellet
  • 505
  • 4
  • 15
  • possible duplicate of [How do I use the conditional operator (? :) in Ruby?](http://stackoverflow.com/questions/4252936/how-do-i-use-the-conditional-operator-in-ruby) – Andrew Marshall Jan 22 '13 at 18:16
  • Maybe this links is useful: https://stackoverflow.com/questions/2151410/c-sharp-auto-highlight-text-in-a-textbox-control – Filipe Freire Jul 10 '17 at 11:35

4 Answers4

6

It's the Ternary Operator.

(condition) ? "true value" : "false value"

It's saying if name == :notice use "success" otherwise "error".

Austin Brunkhorst
  • 18,784
  • 5
  • 40
  • 56
2

This line

result = (name == :notice ? "success" : "error")

Can be tanslated to:

result =""
if(name == :notice)
{
 result = "success"
}
else
{
 result = "error"
}

In your case the result is not a variable, but it's value is pasted to html.

EDIT

I'd like to extend it to support all levels of flash[] messages.

This operator is usually used just for simple true false condition, though if you really want you can use it like that:

name == :notice ? "success" : name == :error ? "error" : "something else"

Consider using this instead (more readable)

if name == :notice
 "success"
elsif name == :error
 "error"
else
 "something else"
end
Andrzej Gis
  • 11,456
  • 12
  • 73
  • 118
1

That code changes the div class dynamically. It checks for :notice and the div class will get:

  • "alert alert-success"
  • "alert alert-error"

depending of :notice result.

Pedro Tavares
  • 949
  • 6
  • 17
0

It's displaying the contents of the flash. Each key-value pair of the flash is displayed as a separate div, with the class of the div depending on the key.

Line 3 is adding a class of alert-success or alert-failure depending on whether the key is :notice or not

Frederick Cheung
  • 79,397
  • 6
  • 137
  • 164