Friday, December 2nd, 2005

Real-world Rails RJS templates

Category: Ruby

Ajax is getting even easier for Rails developers. Scott Raymond has talked about his first use of RJS Templates for IconBuffet.

Using RJS, Scott was able to get rid of a bunch of JavaScript and replace it:

This addition allows you to generate Javascript from Ruby, which can be returned by Ajax calls and evaluated in the page. As usual, I use link_to_remote, Rails’ standard way to create an Ajaxified link:

link_to_remote "Add to Cart", :url => { 
  :action => 'add_to_cart', :id => product }

The controller saves the product id and renders the add_to_cart view—but instead of the usual .rhtml or .rxml template, it’s an .rjs template:

page.replace_html 'cartbox', :partial => 'cart'
page.replace_html 'num_items', :partial => 'num_items'
page.send :record, 
   "Element.addClassName('product_#{@params[:id]}', 'incart')"

These three lines accomplish the same thing as the fourteen lines of Javascript above. The first line renders the ‘cart’ partial into the DOM element #cartbox. The second line does the same thing, but for the header. The third line just creates a line of Javascript to add a CSS class to an element.

Update: Scott Raymond just made a plugin out of RJS, so you don’t need to be running edge rails.

Posted by Dion Almaer at 8:18 am
8 Comments

++++-
4.2 rating from 18 votes

8 Comments »

Comments feed

Thanks for the pointer.

You might want to include the URL of Scott’s post:

http://scottraymond.net/articles/2005/12/01/real-world-rails-rjs-templates

Comment by cboone — December 2, 2005

Duh, Sorry, it’s in there now, as well as the update!

Cheers,

Dion

Comment by Dion Almaer — December 2, 2005

Actually, Cody Fauser made that RJS plugin, not me.

Comment by scott Raymond — December 5, 2005

[…] RJS Templates – This is another HUGE feature. I don’t know anyone that wants to sit down and conjur up Javascript all day long. Well, now we can write Javascript using Ruby. How bad-a$$ is that? Explanations here, here, and here. […]

Pingback by Rails 1.1 is out — March 28, 2006

i am glad to breaking the silence to announce, that
This is such a great resource list of WordPress Templates. I have posted about your site several times on my blog.

No need for anyone else to keep adding to their list when you have it all.

Comment by Smith — May 2, 2006

really a great entry.

Comment by Smith — May 2, 2006

Beauty Tips, Hair Styles, Fashion, models, clothes, beauty, chic, catwalk, UK, collection and More at freewebs.com/getlook

Comment by John — May 5, 2006

rjs – real good thing, very simple!

Comment by sarman — July 18, 2006

Leave a comment

You must be logged in to post a comment.