Friday, August 22, 2008

Tidy Javascripts

So I have been reading the Advanced Rails Recipes book by Mike Clark. Pretty good book.

Recipe 19, Decouple JavaScript with Low Pro, uses Dan Webb's Low Pro Javascript library to pluck the behavior-oriented Javascripts out of the mark-up code and tuck them away into its own section or file. We are basically talking about onxxx events. Neat!

However, the example in the recipe puts the behavior Javascript code in public/javascripts/application.js. This is fine for globally applicable stuff. What about code that is applicable only to views of a specific controller or just a single view?

Taking a cue for my Tidy Stylesheets post, I came up with the following:

  def tidy_javascripts
@javascripts ||= []
["application", "#{controller.controller_path}/_controller", "#{controller.controller_path}/#{controller.action_name}"].each do |javascript|
@javascripts << javascript if File.exists? "#{Dir.pwd}/public/javascripts/#{javascript}.js"
Then, in my layouts, I just do this:

<%= javascript_include_tag "prototype" %>
<%= javascript_include_tag "effects" %>
<%= javascript_include_tag "lowpro" %>
<%= javascript_include_tag tidy_javascripts %>
If you are interested in Low Pro, you can download it from Dan's web site. It's a bit hard to get to, but I think the latest is here.

Oh, and for jQuery fans (I am torn between it and Prototype), there is a port of Low Pro for jQuery. You can read about how to use it, too.

What do you think?

Busy, Busy, Busy...

Haven't added an entry in ... wow, over two months.

What happened, you might ask. Well, among others, I have been busying myself with two things: Ruby on Rails (of course) and Oberin.