-1

I have a list of symbols that correspond to various flash messages:

:is_self
:already_exist
:already_added 
:invited 
:added

Every time I run my method, variable answer is assigned one of these symbols. I assigned to variable message the flash message I want to display:

message = t("flash.#{answer.to_s}")

This works fine. At the end of my method, I have something like:

respond_to do |format|
  format.html { redirect_to url, flash: { info: message } }
end

I would like to change the flash message color (switch between info: success: error:). How can I set a hash variable that would contain the right color for the flash message? I tried something like:

new_hash = { :is_self => "info:" , :already_exist => "info:" , :already_added => "info:", :invited => "success:", :added => "success:", }
flash_color = new_hash[answer]

And then:

respond_to do |format|
  format.html { redirect_to url, flash: { flash_color message } }
end

But I won't work. I have no idea how to give the right syntax.

sawa
  • 165,429
  • 45
  • 277
  • 381
phwagner
  • 11
  • 1
  • 4

2 Answers2

3

Assumed, if you are using twitter bootstrap for style flash, You can save your selection style on application_helper.rb

module ApplicationHelper
  def flash_class(level)
    case level
    when :notice then "alert alert-info"
    when :success then "alert alert-success"
    when :error then "alert alert-warning"
    when :alert then "alert alert-danger"
    end
  end
end

create file _flash_message.html.erb on folder layout and paste this

<div>
  <% flash.each do |key, value| %>
    <div class="alert <%= flash_class(key).to_s %> fade in">
      <a href="#" data-dismiss="alert" class="close">×</a>
      <%= value %>
    </div>
  <% end %>
</div>

and to call the flash you just render in view

<%= render 'layouts/flash_message' %>
rails_id
  • 8,120
  • 4
  • 46
  • 84
0

You're mixing up the syntax a little. The mapping you've got initially:

{ info: message }

is a hash mapping the symbol :info to the value of message. It could be written { :info => message }

In your hash new_hash you're including the colon, which is used in the ruby 1.9 hash syntax to indicate a symbol, in a string. I expect you're getting syntax errors as you're no longer setting up a hash in a valid way.

I think you'll need to use the more traditional hash syntax and specify the symbols in your new_hash. Something like this should work:

new_hash = { 
  :is_self => :info, 
  :already_exist => :info, 
  :already_added => :info, 
  :invited => :success, 
  :added => :success, 
}

with:

flash_color = new_hash[answer]
respond_to do |format|
  format.html { redirect_to url, flash: { flash_color => message } }
end

P.S. It's also slightly confusing that you're calling it flash_color - the colour is only really a by-product of it being styled on the front end. They are really just keys in the flash hash.

Shadwell
  • 34,314
  • 14
  • 94
  • 99