Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

A Flickr-based Introduction to Ruby on Rails 2.0 : Page 3

Want to get started with Rails 2.0? Explore some of the most prominent new features, and learn how to use them to build a simple, but visually attractive, web application based on Flickr.


advertisement
Rails 2.0 Goes the REST Way
One of the major new features of Rails 2.0 is its complete "RESTfulness." It is now extremely easy to publish resources according to the REST (Representational State Transfer) APIs. In fact, you can expose every Rails model—or more correctly, every resource of your application—as an object that you can manipulate, access, and modify using the basic commands of the HTTP protocol (GET, POST, PUT, DELETE). These commands map directly to CRUD (Create, Read, Update, Delete) operations on the exposed resource.

REST support was already available in Rails 1.x, but it is now more integrated and simpler to use. To expose a resource according to the REST principles, you only have to define a Rails controller with the right methods, as shown in Table 1 for the Photo resource.

Table 1. The Methods that a REST Controller Must Provide
Controller Method CRUD Operation Sample URL
index Retrieve all photos GET /photos
show Retrieve photo with ID 123 GET /photos/123
new Retrieve a new photo to edit it GET /photos/new
edit Retrieve existing photo with ID 123 to edit it GET /photos/123/edit
create Create (store) a new photo POST /photos
update Update existing photo 123 PUT /photos/123
destroy Delete existing photo 123 DELETE /photos/123



The updated Rails 2.0 scaffold generator that RailTrackr uses always creates controllers compliant to the Table 1 scheme. Launching the command script/generate scaffold Photo will create the following files and elements:

  • A RESTful controller (photos_controller.rb)
  • An ActiveRecord model (photo.rb) that will be replaced in the sample application with a proxy for the Flickr APIs
  • The associated views (edit.html.erb, index.html.erb, new.html.erb, show.html.erb)
  • A resource mapping inside the routing file routes.rb
  • The usual set of tests, fixtures, and database migration files

Unlike previous Rails versions, the controller name is now automatically pluralized, to reflect resource addressing in REST URLs more properly. Moreover, the view files that are created have completely new name patterns.

Chameleonic Views
Rails 2.0 extends the existing support for multiviews to embrace templates. Each resource can be accessed and manipulated in a variety of different formats, each of them rendered by a particular engine. Views use the filename syntax [name_of_the_view].[format].[engine]. For example, a file called show.html.erb would:

  1. Represent the view associated to the show method of its controller;
  2. Produce html output; and
  3. Use the erb (Embedded Ruby) engine. (Erb is the default engine that was used to create dynamic HTML views in previous Rails versions.)

Following the same pattern, show.csv.erb and show.atom.builder templates map the same view to erb-generated CSV (comma separated values) content and to an ATOM syndication feed generated by the XML builder engine, respectively.

Controllers can use the request.format and respond_to functions respectively to change the rendering format and to forward the execution flow to the appropriate template. If unspecified, Rails uses the mimetype of the requested resource to detect the right template. The following listing shows how the controller method can return a list of photos either as an HTML page or as an XML file:

class PhotosController < ApplicationController # GET /photos # GET /photos.xml def index @photos = # load photos from Flickr respond_to do |format| format.html # index.html.erb format.xml { render :xml => @photos } end end end

RailTrackr renders photos as JPG binary images whenever the user requests a specific image. To accommodate this requirement, you have to change the show method of the controller as follows:

class PhotosController < ApplicationController # ... omissis ... # GET /photos/1.jpg def show @photo = Photo.find(params[:id]) respond_to do |format| format.jpg end end end

Then you have to create the view file views/photos/show.jpg.erb, which will output the binary contents of the image:

<%= @photo.image_data %>

The model object @photo has an attribute called image_data that contains the binary contents of the image itself.

In addition to the default formats (HTML, XML, ATOM, etc.), you can also create custom formats by modifying the file config/initializers/mime_types.rb and using the Mime::Type.register_alias function. Here is a possible configuration that illustrates this feature:

# Bind jpeg mime-type to the format.jpg format Mime::Type.register_alias "image/jpeg", :jpg # Bind the richtext mime-type to the format.rtf format Mime::Type.register "text/richtext", :rtf # Bind an additional formatter to the html mime-type, to be used # for mobile devices with a limited display Mime::Type.register_alias "text/html", :mobile

The last line fulfills the typical requirement of having two different HTML renderings: one for browsers and one for mobile devices with limited display capabilities. A controller can then choose the appropriate rendering depending on some request parameters or HTTP headers. Here is an example of that:

class PhotosController < ApplicationController before_filter :detect_mobile_device def index @photos = # load photos from Flickr respond_to do |format| format.html # index.html.erb format.mobile # index.mobile.erb end end ... omissis ... def detect_mobile_device if request.env['HTTP_USER_AGENT'] && request.env['HTTP_USER_AGENT'][/BlackBerry/] request.format = :mobile end end end

This tutorial describes in more detail how to use custom formats to support mobile devices.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date