Friday, 18 November 2011

Rails3.1 - Manage CSS/JS with Asset Pipeline

An Ideal way to mange your css/js using sprockets in rails (>~ 3) apps. Asset pipeline is enabled by default from rails 3.1 and it uses 'app/assets' to maintain the asset files. We can also have 'lib/assets' and 'vendor/assets' to host the assets.

These assets are included in the layout using

<%= stylesheet_link_tag    "application" %>
<%= javascript_include_tag "application" %>
and the app/assets/stylesheets/application.css will

  *= require_self
  *= require_tree .
Ideally, we wouldn't want to require the whole tree for stylesheets or javascripts. We only need application and the controller specific assets to be loaded on any given page and so I recommended having the following setup.

Typical application.css
*= require reset-min
*= require_self

In layout:

  <%= stylesheet_link_tag    "application", params[:controller] %>
  <%= javascript_include_tag "application", params[:controller] %>
  <%= yield(:head) %>
Hereby, we load only the common styles/scripts applicable for the app, from application and controller specific styles. yield(:head) is to require custom styles/scripts for a page.

Also, assets from vendor/assets or lib/assets can be required within application or controller specific files.

Note: with this approach, the custom files has to be added manually to the precompile list, for them to be precompiled. config.assets.precompile += %w( *.js *.css ) - should do the trick.

No comments:

Post a Comment