So I’ve been learning Ruby on Rails the past few months but I’ve mostly been working on projects that already have the major underpinnings created. I’ve had the opportunity to work on a side project on and off and I’ve finally gotten one of my major hurdles accomplished and am pretty happy with how I did it. I’m open to code refinement, but I thought I’d share it since I couldn’t find much in the way of tutorials regarding flash.now with Rails via Google.

Essentially what I did was implement a way to update the regular flash and the flash.now values at the same time. I also made it very easy to implement a flash message on every page of my site. This flash message will display via a regular HTML request or via an AJAX request if it is invoked. I started by minimizing the code and creating a partial that I can use to render my Flash messages. The catch to this is that anytime you want to update your flash message you’ll have to remember to pass the flash variable to it as a local variable.

Flash Partial (/app/views/layouts/_flash.html.erb)
1
2
3
4
5
6
<%- unless flash.blank? -%>
  <%= flash_message_helper(flash) %>
  <script type="text/javascript" charset="utf-8">
    showFlashMessage();
  </script>
<%- end -%>
Flash Helper (/app/helpers/application_helper.rb)
1
2
3
4
5
6
7
def flash_message_helper(flash)
  html = ''
  flash.each do |type, message|
    html << "<div class=\"flash #{type}\">#{message}</div>"
  end
  return html
end
Flash JavaScript (/public/javascript/application.js)
1
2
3
4
5
6
7
8
9
10
function showFlashMessage() {
  $('flash_wrapper').hide();
  $('flash_wrapper').appear({
    to: 0.9,
    queue: 'end',
    afterFinish: function(ev) {
      setTimeout("$('flash_wrapper').fade()", 4500);
    }
  });
}
Controller Method Code (/app/controllers/controller_name.rb)
1
2
3
4
5
6
7
8
9
10
11
def method_name
  respond_to do |format|
    format.js {
      render :update do |page|
        flash_message('notice', 'Page was successfully updated.')
        page.replace_html 'show', :partial => 'show'
        page.replace_html 'flash_wrapper', :partial => 'layouts/flash', :locals => {:flash => flash}
      end
    }
  end
end

You’ll notice in the controller I invoke a custom method (flash_message) to create my flash message. This is where we create the flash[] and flash.now[] values simultaneously.

Application.rb Code (/app/controllers/application.rb):
1
2
3
4
5
6
7
8
9
def flash_message(type, message)
  flash.discard(type.to_sym)
  if request.xhr?
    flash.now[type.to_sym] = message
  else
    flash[type.to_sym] = message
    flash.keep(type.to_sym)
  end
end

And lastly you need to place the partial in your page templates:

1
2
3
<div id="flash_wrapper">
  <%= render :partial => 'layouts/flash', :locals => { :flash => flash } %>
</div>

Comments