Amazon

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:

application_helper.rb
  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"
end
@javascripts
end
Then, in my layouts, I just do this:

some_layout.html.erb
<%= 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?

No comments: