2

I'm trying to make rails' flash messages style with bootstrap 3.

In this piece of code,

    <% flash.each do |key, value| %>
      <div class="alert alert-<%= key %>"><%= value %></div>
    <% end %>

<%=key> puts the key into the class tag like you'd expect. But when I change the middle line to this

<div class="<%= flash_class(key) %>"><%= value %></div>

<%= flash_class(key)%> doesn't embed anything.

flash_class() is in application_helper.rb which is automatically included in views (right?) and it returns a string. I think it's probably something stupid I'm missing, why does this not work?

edit- here's the implementation of flash_class

   def flash_class(level)
        case level
            when :notice then "alert alert-info"
            when :success then "alert alert-success"
            when :error then "alert alert-error"
            when :alert then "alert alert-error"
        end
    end
NathanTempelman
  • 1,301
  • 9
  • 34

1 Answers1

2

Probably a problem comparing string with symbols:

def flash_class(level)
  case level.to_sym

Should solve your problem

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • This is basically what I'm doing, only I'm formatting the class name to work with bootstrap. The bootstrap alert names and rails' flash keys aren't the same. – NathanTempelman Jun 05 '14 at 15:07
  • @NathanTempelman I updated my answer with an `else` statement in the case + `.to_sym` on `level` variable – MrYoshiji Jun 05 '14 at 15:12
  • I tried your else statement, and it put out "key not recognized". then I replaced it with level, and it came back as "notice". Then I tried your to_sym, and now it works. I guess you can't compare strings and symbols? And also I guess keys are always symbols? – NathanTempelman Jun 05 '14 at 15:23
  • Update your answer to include the symbol comparing shenannigan, and I'll accept it. Thanks for the help – NathanTempelman Jun 05 '14 at 15:30
  • No, keys can either be string or symbol. A HashWithIndifferentAccess is the same as a Hash except that you can access a value with either the key as a string or as a symbol. Your `flash` variable is a simple Hash, not HashWithIndifferentAccess -- @NathanTempelman my answer already uses a `.to_sym` on the key, what do you want me to change? – MrYoshiji Jun 05 '14 at 15:31
  • I guess shorten it? The only bit of my code that didn't work was the to_sym bit, and that detail kind of gets lost in your answer. Just mention I'm an idiot and was comparing strings and symbols (PS why doesn't that just work?) – NathanTempelman Jun 05 '14 at 15:37
  • You can do `flash.with_indifferent_access` to be able to do either `flash[:error]` AND `flash['error']` – MrYoshiji Jun 05 '14 at 15:44
  • Won't I be able to do that anyway? Because it's converted to a symbol either way right? – NathanTempelman Jun 05 '14 at 16:47