1

Or: How can I structure the code in my application.js file of my Rails 3.0.10 app, or distribute it (logically) among various files so that I know what the bleep is going on?

Currently my application.js is running to 700 lines of code. It's mostly flat with lots of jQuery bits like:

//////////// the following code is for the need_email_confirmation page and user_sign_in page
$('body').delegate('#sign_up_resend_confirmation', 'click', function(event) {
  event.preventDefault();
  $('form#new_user').submit();
});

Sometimes I use comment delimiters as above to make different sections, but it seems kind of ... (is it ok to say "ghetto"?). Lots of code like the above, all inside of a $(document).ready(function() {... piece. Sometimes I want to prevent too much indenting so I write a top-level function, something like:

$('body').delegate('#new_canvas_item_cancel', "click", hideEditorAndPreventServerHit);
$('body').delegate('#edit_canvas_item_cancel', "click", hideEditorAndPreventServerHit);

function hideEditorAndPreventServerHit(event) {
  $(this).closest('div.new_item_div, div.edit_canvas_item').slideUp();
  event.preventDefault();
}

What are the best practices?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Purplejacket
  • 1,808
  • 2
  • 25
  • 43

2 Answers2

0

You didn't mention what specific Rails version you are on, but if you have the flexibility to stay up to date, try taking advantage of the Rails asset pipeline. (need Rails 3.1)

http://guides.rubyonrails.org/asset_pipeline.html

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
0

Looks like you want Rails 3.1. It introduced an asset pipeline that allows you to break up your Javascript and CSS into small files that are automatically compiled into production-ready files.

You can even use abstractions over Javascript and CSS (Coffeescript, SCSS or even ERB templates) that are automatically compiled to JS and CSS.

The basic idea is that your application.js is placed inside app/assets/javascripts and contains the following to include all other JS files in that directory:

//= require_tree .

See more in the Rails guide!

molf
  • 73,644
  • 13
  • 135
  • 118
  • Thanks that helps. Additionally, what are some guidelines as to how to break up the code? Is it just one file per "theme", or is there some way that the Rails framework can formally associate a particular .js file with some type of functionality (members, projects, blog posts, what have you)? – Purplejacket Oct 06 '11 at 23:38
  • It's up to you. Split it up into functional parts, I would say. Be specific in the names you give the files, and create subdirectories if necessary! – molf Oct 06 '11 at 23:44