Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - how require is executed in application.js

I am reading a book for "Ruby on Rails". In the "application.js", we are including other JavaScript libraries in the following way and more specific - jQuery UI:

//= require jquery
//= require jquery_ujs
//= require jquery-ui

As this is ordinary JavaScript file (not ruby extensions here like "html.erb" for exmaple) how the application knows to execute the require command? What kind of JavaScript syntax is this:

//= 

and as this is ordinary JavaScript file, why we are not using "script" tags to include JavaScript files?

Also, I have read here that "require" method will check for this library in define by $LOAD_PATH variable folders. How can I see where the "jquery-ui" is stored? I am asking because in other applications in order to use jQuery UI I should add not only JavaScript file, but css file and images used by the library - in this case, we are doing this only with single line?

like image 537
gotqn Avatar asked Nov 04 '12 11:11

gotqn


1 Answers

What kind of JavaScript syntax is this.

Anything starting with a // is a Javascript comment.

How is it able to process it ?

Sprockets on the server side scans the JS file for directives. //= is a special Sprocket directive. When it encounters that directive it asks the Directive Processor to process the command, require in this example. In the absence of Sprockets the //= require .. line would be a simple JS comment.

Ruby require vs Sprockets require

These are two completely different things. The one you link to is Ruby's require.

Why not use script tags to load JS files.

Usually, you want to concatenate all your app JS files and then minify them into 1 master JS file and then include that. I recommend reading the YSlow best practices on this.

I also recommend watching the Railscasts on Asset Pipline - http://railscasts.com/episodes/279-understanding-the-asset-pipeline

Cheers!

like image 168
Akshay Rawat Avatar answered Sep 29 '22 06:09

Akshay Rawat