Recently I’ve started to favour using small snippets of js.erb for each controller action over using one monolithic javascript controller designed to run the whole application. It means you have small manageable pieces of code which are only loaded when the app needs them, this is also good for your sites security as you do not expose everything at once in a .js file.
The problem I had was that I need to make sure notices are shown on ajax requests as well as normal requests. I started out by having a block of code at the bottom of each js.erb that would show notices like so:
%('#notices').replaceWith('<% escape_javascript(render :partial => "shared/notices")%>');
Which was all well and good except it’s not DRY, and didn’t feel very rails at all. My final solution involved using application.js.erb in layouts, which I didn’t even realise was possible. Check it out:
#application.js.erb
<%= render :partial => "shared/notices" %> <%= yield %>
#shared/notices.js.erb
if($('#notices')){
$('#notices').replaceWith('<% escape_javascript(render :partial => "shared/notices.html")%>');
}else{
notices = $('#header').before('<% escape_javascript(render :partial => "shared/notices.html")%>');
}
#shared/notices.html.erb
<% if flash[:notice] %><%= flash[:notice] %><% end %> <% if flash[:error] %>>%= flash[:error] %><% end %%gt; <%= link_to "close", "#", :class => "close" %> <% javascript_tag do %> noticesTimer = setTimeout(function(){ $('#notices').slideUp()}, 5000); $('#notices .close').click(function(){$('#notices').slideUp(); return false; }); <% end %>
It will only load notices if needed, replace any #notices if it already exists and self hide afterwards.









Thanks for posting this little tidbit. I was just wondering how to render flash messages when doing ajax posts.
Thank you again,
Eric