views:

217

answers:

2

Hi,

i'm working in a big and rich rails web application using tons of javascript. I would like to know if anybody has a tip to organize the javascripts. Today i'm generating a new file named controller.js and adding it to my views using content_for. The problem is, some files are becoming big and sometimes, i need a function from one controller in another, so then in the end, i add a products.js to a details controller just to keep DRY. Is that solution good? Any other tip? I think the same pattern can be applied as well to css files?

+2  A: 

You've got conflicting demands here because you want your JavaScript files to be nice and modular for maintainability during development, but in production you want them to be combined to minimize the number of HTTP requests made, thus improving performance.

Personally I've found Jammit to be a good solution for managing these apparently conflicting aims. It's a gem that packages your assets (CSS and JavaScript) and as a bonus can compress them too.

John Topley
i don't care about production. I think my problem is to keep it easy to new developers to get used with this code.
VP
Well you should care about production at some point!
John Topley
sure i care, i mean, AFAIK the organization won't be a problem at production if i use something like Jammit since it will compress everything in one file, no?
VP
Yes, it lets you have how ever many you want in production.
John Topley
Sprokets is another library for managing javascript inclusion which might work well for you @VP. http://getsprockets.org/
Tim Snowhite
+1  A: 

I actually just posted my current approach to organising JS in Ruby on Rails.

I have a namespaced JavaScript file for each of my controllers and then I use asset_packager to bind these many small files into a single file at deploy time.

You could make this more granular and have a file for each action in a controller, but it means I have many small files scoped to small elements of functionality in the my system.

Works really well.

Toby Hede
it's more or less what was proposed here http://dailyjs.com/2010/04/27/unobtrusive-js/
VP