Rails plugin: AssetAutoInclude

Tags
Posted
Thu 16 Oct, 2008
Comments
0

AssetAutoInclude is a new Rails plugin written by Gabriel (who helps me out with Helicoid’s projects and works on Rails projects for all kinds of big companies in the US). It’s designed to make JavaScript and CSS includes more efficient, by only including the JavaScript or CSS you require for each controller and action.

The motivation for this project is to:

  • Help manage your CSS and JavaScript in a familiar Rails-friendly way
  • Only include the required CSS and JavaScript on each page

This is in contrast to the common technique of appending JavaScript or CSS into monolithic files.

Usage

Install using script/plugin:

  script/plugin install git://github.com/gabrielg/asset_auto_include.git

By adding the following to a layout:

 <%= javascript_auto_include_tags %>
 <%= stylesheet_auto_include_tags %>

You’ll get JavaScript and CSS automatically included according to the following scheme:

 mydomain.com/users             # includes controller.js and controller.css
 mydomain.com/users/edit/1      # includes controller.js, edit.js, and edit.css
 mydomain.com/users/show/1      # includes controller.js
 mydomain.com/roles             # includes roles.js
 mydomain.com/accounts          # no files included
 mydomain.com/accounts/show/1   # includes show.js and show-new-edit-create.js
 mydomain.com/accounts/new      # includes show-new-edit-create.js
 mydomain.com/accounts/edit/1   # includes show-new-edit-create.js
 mydomain.com/accounts/create   # includes show-new-edit-create.js

This allows you to share JavaScript in controller.js files, and add action-specific includes where required. Many controllers have shared JavaScript, with only minimal tailoring for add/edit actions, so this makes sense for most instances.

The plugin only includes assets that exist, so you don’t need to create empty files for controllers or actions you don’t need.

Expected JavaScript and CSS file system layout

The expected file structure is as follows:

 /public
   /javascripts
     /app
       /users
         controller.js
         edit.js
       /roles
         controller.js
       /accounts
         show-new-edit-create.js
   /stylesheets
     /app
       /users
         controller.css
         edit.css

This makes managing your JavaScript files easier, and more consistent with the Rails style too.


Security Code