Chapter 5. RJS

If you picked up this book for the first time and skipped directly to this chapter, I don’t blame you. And if you’re the linear type and have read all the previous chapters, everything has been leading up to this: Ruby-generated JavaScript (RJS) is the capstone of Ajax in Rails.

In the last few chapters, practically all the Ajax examples have one thing in common: they work by receiving small snippets of HTML from the server and inserting them into the page. It’s a delightfully simple approach, and it gets a ton done with a minimum of abstraction overhead. After all, we’re building web applications, so everything will eventually become HTML anyway. Rails has a rich set of helpers for generating HTML, so why not simply render that on the server side and transfer it as is. But sometimes the simple approach isn’t sufficient—sometimes you need more flexibility.

Instructions Instead of Data

The Rails solution is to return JavaScript instructions, instead of HTML data, to Ajax requests. The JavaScript is executed as it comes in, so it can do anything that’s possible from scripting—insert new content into the page, create visual effects, call methods from external JavaScript libraries—you name it. And you can include as many JavaScript statements as you need in one response, so it’s trivially easy to update a bunch of page elements at once. Try that with the standard link_to_remote :update => ... helper and you’ll quickly appreciate how valuable JavaScript can be.

The power ...

Get Ajax on Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.