more info

Media72 Hosting Articles and Tips

Javascript auto include rails plugin

This plugin has been updated to include additional functionality.

We are very pleased to announce the javascript_auto_include plugin for ruby on rails written by our very own Jamie Dyer. This plugin automatically includes javascript code that is specific to a single 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 javascript that is not unobtrusive.

When writing unobtrusive javascript in Rails it’s often necessary to include a javascript file that will be used by a single view or controller. This can become problematic, messy and very un-Rails like if not managed well.

With the Rails philosophy “convention over configuration” in mind I decided to create a plugin to automatically including javascript files that correspond to the view or controller name mirroring the view structure within the javascripts folder. The javascript_auto_include plugin is born and is probably among the smallest Rails plugins available, aren’t all the best plugins tiny?

To use the javascript_auto_include firstly install the plugin:


script/plugin install http://kernowsoul.com/svn/plugins/javascript_auto_include

Or if you run EDGE rails or rails 2.1 and 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

If you have any comments or suggestions for improvements we would love to hear them. I may add a generator to make adding new javascript files easy.

Leave a Reply

 

hedges