How do I keep application.js in my Rails app from getting too big, and how do I structure it?
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?
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
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!
精彩评论