Sam Stephenson has recently released a Javascript preprocessor called Sprockets. It’s distributed as Ruby gem, and it helps to declare scripts dependencies through special comments, and safely build them one script. It’s very useful for maintain your Javascript projects, extract reusable code and share across applications.

Installation

$ (sudo) gem install sprockets It will also install sprocketize executable.

How it works?

To declare a dependency use require directive:
//= require //= require "cookies" When you use angular brackets the script will be searched in all the Sprockets load path, if you use quotes instead, you are forcing to load the file from the current directory. Usually you should use the first way to require frameworks or libraries and the second one for your scripts.

How it works with Rails?

Sam has wrote a plugin to use Sprockets with Rails, let’s install it:
$ ./script/install plugin git://github.com/sstephenson/sprockets-rails.git It automatically creates two folders: app/javascripts and vendor/sprockets.

Move all the files from public/javascripts to the first folder.

Now let’s sprocketize our files: /* controls.js */ //= require //= require

/* dragdrop.js */ //= require //= require

/* effects.js */ //= require

/* lowpro.js */ //= require

/* prototype.js */ // nothing to do

/* application.js */ //= require //= require //= require //= require //= require

/* comments.js */ //= require //= require “application” Of course application.js and comments.js configurations depends on which libraries you need for your scripts.

One last step, we have to configure our routes with:
# config/routes.rb SprocketsApplication.routes(map)

Now forget about javascript_include_tag helper and place one time at the bottom of your template:
sprockets-rails will provide all the scripts needed by your application.

Advanced sprocketing

Sprockets help you to bundle all kind of assets (HTML, CSS, images) your Javascript project needs. Imagine to have a plugin with assets and javascripts folders, in your script you can declare:
//= provide "../assets" Just running sprockets:install_assets rake task, sprockets-rails will copy all the assets and scripts to the public folder.

If you want to use the edge of favorite javascript frameworks like jQuery Sprockets will bundle for you. For example if you want to add Prototype’s edge, just copy src folder under vendored folder of Sprockets:
vendor/sprockets/prototype/src

Deployment

Add sprockets:install_script as Capistrano post-deploy hook to generate the all-in-bundle script.

One more thing

If you use assets_packager, I just committed a sprocketized version of rake tasks.