Since the introduction of the asset pipeline, managing javascript assets in a typical rails application is pretty straight forward. You figure out some structure for organizing the files under app/assets/javascripts/
, concatenate them together with some directives in application.js
, and that file is most likely included in a layout and you’re on your way. But what about those pesky page specific initializer scripts?
A popular approach is to use a strategy like this. The gist of this approach is to organize your page initializers in an object literal by controller name and action, something like
initializers: foos: index: -> show: ->
The document body is decorated with the current controller name and action. A document ready script extracts the controller and action, looks it up in the initializers object and executes the associated initializer. Generally the initalizer scripts are placed somewhere under app/assets/javascripts
and included in the application.js bundle. This approach is perfectly fine, but a few minor things bug me:
An approach that has worked for me looks something like this:
I like this approach for a few reasons:
The downsides:
You probably noticed the code at the bottom of the application.js file. This code doesn’t specifically have anything to do with the loading strategy outlined above, but it does complement it. It creates a namespace for your JavaScript, named after your rails app. Within this namespace it creates a page object. This object provides a few things:
This is obviously just one of many approaches out there. What other approaches have worked for you?