Rails javascript specific layout

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] %>
&lt% 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.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • StumbleUpon
  • Twitter

About Danny

Primarily a Ruby On Rails developer, but I can do other cool stuff too.
This entry was posted in Development, Ruby / Rails and tagged , , , . Bookmark the permalink.

One Response to Rails javascript specific layout

  1. Eric Krause says:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>