O'Reilly logo

Ajax on Rails by Scott Raymond

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Putting the R in RJS

The kicker is that instead of writing the JavaScript by hand, Rails generates it. That’s where RJS, Ruby-generated JavaScript, comes in. RJS is Ruby code that generates JavaScript code, which is sent as the result of an Ajax call. Whereas most actions render data (from .rhtml files or otherwise), RJS is different—it renders instructions. Of course, the instructions sent to the page often contain content (e.g., change the text in that box to this), but it’s always within the context of JavaScript code.

The obvious consequence of using Ruby to generate JavaScript is that more of your application is written in Ruby, which drastically simplifies development. As a developer, it’s just easier to think in one language, rather than mentally switching gears between Ruby and JavaScript. (Not to mention that we Rails developers tend to love writing Ruby, so we’re always looking for new places to put it.)

The Ruby language is well suited for creating Domain Specific Languages (DSLs), mini-languages tuned to a particular task. The most common exemplar of a DSL in Ruby is Rake, Ruby’s make-like build system. RJS is another fine example—think of it as a DSL for generating JavaScript. In fact, once you become accustomed to using RJS, you may start to forget that JavaScript is being used behind the scenes; RJS just feels like a magic remote control for the browser.

Diving In

Eager to see how it all works? Let’s look at some examples. To set the stage for the examples in this ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required