Previous Page
Next Page

Hack 57. Make Your JavaScript Available to Rails Applications

Call custom JavaScript functions in Rails templates without including long script tags.

Even though Ruby on Rails takes care of a lot of the JavaScript-related functionality in Ajax applications with its own methods, you still may want to have access to your own JavaScript functions. This is particularly true if you come to Ruby on Rails with a JavaScript background. This hack uses the RoR setup to call a JavaScript function that does not come with Ruby on Rails or its included packages. Here's the drill.

Figure 7-8 shows a typical Rails web directory setup, with the contents of the public directory revealed. This directory includes a subdirectory named javascripts, which in turn contains a file called application.js, into which you can write or cut and paste your function. RoR creates the application.js file for you when it auto-generates the core directories and files for a web application.

Figure 7-8. application.js in the javascripts directory


Now, back up a bit to a template you are using. The monitor.rhtml template referred to in the last hack includes this embedded method call:

<%= javascript_include_tag :defaults %>

The code includes the defaults parameter with javascript_include_tag( ), which automatically generates the script tag importing application.js, along with a bunch of other Prototype- and script.aculo.us-related imports (see Chapters 6 and 8, respectively, for discussions of the Prototype and script.aculo.us libraries). As a result, the JavaScript in application.js is available for code in the template to call. For example, monitor.rhtml includes this code:

<div id="complete" style=
"font-size: 1.2em; color: green" onclick="clearIt($('complete'))"></div>

clearIt( ) is defined in application.js. It sets the innerHTML property of the element referenced by its parameter to the empty string "":

function clearIt(elId){
    if(elId != null){
        elId.innerHTML="";
    }
}

Using javascript_include_tag( ) involves a single step for importing application.js and any other necessary packages (such as Prototype), but you are certainly free to place your own JavaScript file in the javascripts directory and then include a script tag to import it in the Rails template:

<script src="/javascripts/myfunctions.js" type="text/javascript"></script>

You can use javascript_include_tag( ) with different parameters to import individual JavaScript files, as in these two examples:

javascript_include_tag "/javascripts/myfunctions.js","/scripts/morefuncs.js"
#As long as the scripts directory is located in 
#the Rails <web-app-root>/public directory


Previous Page
Next Page