ruby-on-railsrubytwitter-bootstraphelperactiveview

Rails Display Bootstrap Alerts Using Helpers


I am trying to follow this Gist to display Bootstrap alerts for a crud rails app https://gist.github.com/suryart/7418454. The contents of which have the code:

application_helper.rb:

module ApplicationHelper

  def bootstrap_class_for flash_type
    { success: "alert-success", error: "alert-danger", alert: "alert-warning", notice: "alert-info" }[flash_type] || flash_type.to_s
  end

  def flash_messages(opts = {})
    flash.each do |msg_type, message|
      concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} fade in") do 
              concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' })
              concat message 
            end)
    end
    nil
  end

application.html.erb

<body>
    <div class="container">

      <%= flash_messages %>

      <%= yield %>
    </div><!-- /container -->
</body>

Problem is I am not seeing any of the messages displayed.

I thought that maybe since the gist is showing to return nil that maybe I need to return the contents of the .each iterator so I did something like this in my helper to return the html:

  def flash_messages
    @flash_msg = ""
    flash.each do |msg_type, message|
      @flash_msg = concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} fade in") do
                    concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' })
                    concat message
                  end)
      puts "@flash_msg: #{@flash_msg}"
    end
    @flash_msg
  end

But when you look at the output of the print statement it is showing me the enter HTML for the page, the end of which is actually the html I need:

<div class="alert alert-info fade in"><button class="close" data-dismiss="alert">x</button>Signed in successfully.</div>

How do I get this to work so that it only returns that last part and not the entire page?


Solution

  • You should use non-output code block: <% flash_messages %> (Not <%=) along with the original code of your gist.

    concat is responsible for injecting the html markup in the template context and the return value of the helper has no significance.