javascript_auto_include Rails Plugin
The javascript_auto_include plugin automatically includes javascript code that's required by a specific view or controller which means you don’t have to pass anything to your template telling it which javascript files are needed for each page.
Working with unobtrusive javascript in Rails can be somewhat difficult. While Rails default javascript helpers are easy to use they produce obtrusive javascript.
When writing unobtrusive javascript in Rails it’s often necessary to include a javascript file that will be used by a only a small number of pages within your application. This can become problematic, messy and very un-Rails like if not managed well.
With the Rails philosophy “convention over configuration” in mind the javascript_auto_include plugin automatically includs javascript files that correspond to the view or controller name mirroring the view structure within the javascripts folder.
To use the javascript_auto_include firstly install the plugin:
script/plugin install http://kernowsoul.com/svn/plugins/javascript_auto_include
If you run rails 2.1 or above:
script/plugin install git://github.com/kernow/javascript_auto_include.git
The plugin will create the directory “views” within your javascripts directory in which you can place javascript files for auto inclusion. Using javascript_auto_include is simple, in the layout file add <%= javascript_auto_include_tags %> to the header.
There are two types of javascript includes, view specific, and controller specific. The first is achieved by creating a folder with the same name as a controller, inside this create a javascript file with the same name as a view. The second type, controller specific, are simply files inside the views folder with the same name as the controller. For example:
/public
/javascripts
/views
articles.js # will be included in all views of the articles controller
/users
new.js # will be included in the new view of the users controller
The plugin will also include both controller and view specific javascript at the same time, in this example both users.js and new.js will be included when the new view is loaded.
/public
/javascripts
/views
users.js
/users
new.js
But that's not all, sometimes you may want to include the same javascript file in several views. You can achieve this easily by using the "-" delimiter character to separate your view or controller names. For example, to include a javascript file in your new and edit view create a file called new-edit.js. You can string together as many views or controllers in the filename as you like.