November 01, 2005
Product Review: Railing on AJAXRick Wayne
The Ruby on Rails Web application framework can jump-start 24-carat Web development, and the Asynchronous JavaScript And XML libraries sweeten the GUI pot.The catch: You'll have to code in Ruby.
Software Development
Railing on AJAX
The Ruby on Rails Web application framework can jump-start 24-carat Web development, and the Asynchronous JavaScript And XML libraries sweeten the GUI pot. The catch: You'll have to code in Ruby. By Rick Wayne
Some of us are conservative. Cynical, even. But some are Gadget Boys and Girls, launching projects atop the latest, hottest tech. Some even rip working code asunder to hack in the sweet smell of the new. Initially a Gadget Boy, I was bludgeoned by promising-but-failed technology until cynicism grew on me like a fungus.
For me, Asynchronous JavaScript And XML (AJAX) and Ruby on Rails have proven effective fungicides. Friends, there is a genuinely new way to program Web apps. You can craft a gracile, adaptable GUI that runs in a browser but is as quick on its feet as a merengue dancer, then marry it to a robust model-view-controller (MVC) back-end framework that can produce a prototype database-driven Web app in less time than it takes to type these words.
But sporulating cynics take note: Jumping into AJAX and Rails does risk accepting the dreaded Early Adopter mantle (I used Rails 0.13 here). Plenty of production sites use Rails; Google's use of AJAX hardly needs mentioning. However, the APIs are still in flux, tools are only now hitting the market, and a handful of books were available at press time. And, of course, you'll have to learn Ruby, a language many still consider to be an upstart Python clone.
Have the lightweights and codgers fled? Excellent. I'll get started.
First, AJAX and Rails are by no means inseparable, but their synergy impels me to consider them as a partnership. AJAX, which obviates the Submit button in favor of live updates to pieces of a browser document, hooks quite nicely into the Rails application framework, whose clean separation of concerns and emphasis on convention over configuration (to say nothing of writing code) let you ramp up applications quickly and evade the Big Ball of Mud antipattern. I'll examine the application framework first, and then see how AJAX can make its GUIs sing.
Hello Rails
For Windows, I recommend the One-Click Ruby Installer, which includes the RubyGems package manager (akin to Perl's CPAN). Ruby comes with Mac OS X and most Linux distributions. Or simply download the language from www.ruby-lang.org, and RubyGems from http://docs.rubygems.org. Then installing Rails is simple. From a command-line window, issue the command: gems install railsinclude-dependencies. That and a database (see "System Requirements" in the Product Information box) will have you up and running. Rails' built-in Web server lets you prototype without mucking up your IIS or Apache installation.
Downloading and installing was so fast and straightforward that, as I wrote this, I just stuck it on whatever machine I happened to be working onit wound up on our departmental Apache/Linux server, a Windows machine, another Linux box and my Mac.
Once installed, it's astoundingly easy to get a Web application running. A
simple
Customizing your application means working in three kinds of files: Ruby source, HTML (optionally containing embedded Ruby à la PHP or JSP) and configuration files. There are precious few of the latterRails emphasizes convention over configuration, so processes like object-relational mapping happen for free. For instance, I had a table in my application's MySQL database called items; Rails automatically created a class called Item and populated it for me.
You'll probably recall that in the MVC architecture, model refers to the meat of an application, the data and the business logic that operates on it. The user sees views, which obtain and display model data. The controller takes in user data from the views, calls the model as necessary, and decides which view to present next. So in Rails, the canonical way to construct "Hello World" is to build a
[rick@ubadcat]$ script/generate controller Say
exists app/controllers/
exists app/helpers/
create app/views/say
exists test/functional/
create app/controllers/say_controller.rb
create test/functional/say_controller_test.rb
create app/helpers/say_helper.rb
That's it? Yep. Our application will now respond to
class SayController < ApplicationController
def index
@someMessage = "Say What?" # Don't know what to say!
end
end
Finally, the controller needs a view to present to the user. Again, by convention, the index view for the
<html>
<head><title>Saying...</title></head>
<body>
<h1>What I'm sayin' is "<%= @message %>"</h1>
</body>
</html>
One more wrinkle: Instead of calling the
class SayController < ApplicationController
def index
@someMessage = "Say What?"
end
Supply a "hello" view, and you're done (see "Hello, World!"). As for the model, Rails can produce a straw-man "scaffold" create/read/update/delete (CRUD) application for a database table with a single call to the generate script. From there, you edit the generated Ruby class files to enforce your business rules. Simple validationfor example, to ensure that values have been supplied for required fieldscan be a one-liner.
Getting Real
As I elaborated on my own applicationno toy, this: It's an instructional-support tool for a university classI came to appreciate the Rails philosophy of ruthlessly eliminating repetition (a.k.a. DRY, for "Don't Repeat Yourself"). Except for the fairly explicit contracts between components, changes made in one place tend not to have the ripple effect that makes working with some frameworks so frustrating.
I was sold on test-driven development long ago, but have always found my Web applications to be tough testing customers. Unless you're fairly disciplined about your architecture, or use a framework, it's easy to fling some embedded code into some HTML and wind up with something that can be tested only by a human running a browser. Rails' MVC design, like that of Java Server Faces or Apache Struts, helps keep your code divisible into testable pieces. Rails goes further, though, building a unit-testing framework into your application from the very start. It's easy to set up tests for your models and controllers, especially given Rails' built-in support for canned test datasets (that are automatically emptied between unit tests) and its clever use of an introspection-like technique that streamlines many asserts into one-liners.
Hello AJAX
It's perfectly possible to code the whole works yourself in JavaScriptif you're insane. Better to leverage the existing JavaScript libraries, which insulate you from the gory details. Better still, do it from within Rails, which not only provides you with several useful libraries, but wraps them in the framework so that you hardly need lift a finger to use AJAX.
Let's build a toy application that echoes the HTTP request
class WhoAreWeController < ApplicationController def index end
We'll also need a view. Note the
<html>
<head>
<title>Who's Having This Conversation?</title>
</head>
<body>
<h2>Who are we, anyway?</h2>
<div id="answer_div">
For the answer to this deep philosophical question...
<%= link_to( "click here",
:action => :saywho ) %>
</div>
So far, nothing earth-shattering; the browser shows a new page giving the local and remote addresses when you click the link. Watch my hands, ladies and gentlemen, as I prestidigitate AJAX into this application! First, we'll need to include the
<html>
<head>
<title>Who's Having This Conversation?</title>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<h2>Who are we, anyway?</h2>
<div id="answer_div">
For the answer to this deep philosophical question...
<%= link_to_remote( "click here",
:update => "answer_div",
:url =>{ :action => :saywho }) %>
</div>
Granted, this little example could just as easily be done with a page refresh. But as page complexity grows, the traffic and time to generate go up. Bear in mind, too, that AJAX gives you even more flexibility. Every click, hover or keystroke is grist for the JavaScript event loop, so that you can build lists that autofill as user types, or cache database lookups as the user hovers over a map. AJAX and Rails support more sophisticated modes of interaction, too; you can define callbacks, generate live progress feedback, or add a bevy of special effects, including scaling, fading or elements that vanish in little puffs of smoke.
Should You Rail on AJAX?
AJAX, by itself or combined with Rails, is an even easier call. It takes no great prescience to predict that page-at-a-time, fill-out-and-submit Web apps are going to be looking mighty stodgy in a year. The only reason not to start adopting AJAX today is if you can't get it to meld seamlessly with your current application framework. But put it together with Rails, and you're hummin'.
New & Noteworthy Editor Rick Wayne has way too much fun with Web-enabled ecosystem management software at the University of Wisconsin. E-mail him at fewayne@facstaff.wisc.edu.
|
|
|||||||||||||||||||||||||||||||||||||
|
|
|
|