14.6. AjaxAll this discussion of Ruby leaves us with only one question: Where the (fill-in-the-blank) does Ajax fit in? Well, remember Rails from Chapter 13? That is where Ajax fits in, but for me to prove it, we have to generate another controller (see Figure 14-1). Figure 14-1. Generating a controllerWe're interested in two files: sample_controller.rb under madscientist\ app\controllers, and index.rhtml under madscientist\app\views\sample. The first file is the Ruby application controller that defines the sample class. This class, shown in Listing 14-6, will do all our server-side dirty work. The purpose of the second file (see Listing 14-7), on the other hand, is to handle the client-side part of the Ajax demo. Listing 14-6. controller.rb
Listing 14-7. index.rhtml
After these two files have been modified, in the case of controller.rb, or created, as index.rhtml needs to be, we're ready to start WEBrick (see Figure 14-2) and bring up the page (see Figure 14-3). Figure 14-2. WEBrickFigure 14-3. Generated pageThis leaves just trying out the page, whose sole purpose is to echo back from the server anything entered in the text box when the button is clicked. Figure 14-4 shows the result. Figure 14-4. Echoed textBecause I'm one of those people who needs to know how something works, I've included Listing 14-8 showing the generated HTML. Listing 14-8. Generated HTML
Interesting isn't it? The source from index.rhtml transmogrifies into some pretty neat HTML, with all the Ajax goodies built right in. The javascript_include_tag includes prototype.js, in which resides all the necessary client-side JavaScript, while the rest of the tags describe an HTML form. Personally, I am beginning to feel like I have found the Promised Land, and I'm not leaving. In roughly 24 lines of code, we've got a simple Ajax application. Of course, there is more to it than that; this example only touches upon some of the features available in the Rails API. But Ruby on Rails shows some definite promise. |