Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

230 | Chapter 7: REST, Resources, and Web Services


We can examine the client’s log to find a fairly standard-looking request and
response:


Processing ProductsController#index (for 127.0.0.1 at 2007-09-14
14:30:36) [GET]
Session ID: BAh7Bi...
Parameters: {"action"=>"index", "controller"=>"products"}
Rendering template within layouts/products
Rendering products/index
Completed in 1.02543 (0 reqs/sec) | Rendering: 0.19423 (18%) |
DB: 0.00000 (0%) | 200 OK [http://localhost/products]

But, as you may notice here, there is no “Product Load” entry indicating a database
call. If we look at the server’s log, we notice that the client issued aGETrequest from
ActiveResource forhttp://localhost:4000/products.xml to load the list of products:


Processing ProductsController#index (for 127.0.0.1 at 2007-09-14
14:30:38) [GET]
Session ID: 04bc0d4b88c250a9cd50fb481991e2d9
Parameters: {"format"=>"xml", "action"=>"index",
"controller"=>"products"}
Product Load (0.000591) SELECT * FROM products
Completed in 0.15692 (6 reqs/sec) | Rendering: 0.00255 (1%)
| DB: 0.00059 (0%) | 200 OK [http://localhost/products.xml]

We can see the XML wire protocol that ActiveResource uses by querying the web
service directly—just navigate tohttp://localhost:4000/products.xml. The response is
generated by the ActiveRecord XmlSerializer, [email protected]_xml:


<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<created-at type="datetime">2007-09-08T14:06:08-05:00</created-at>
<description>Description of the T-shirt</description>
<id type="integer">1</id>
<name>Organic cotton T-shirt</name>
<price type="float">18.5</price>
<quantity type="integer">15</quantity>
</product>
</products>

Of course, real-world applications will be more complicated than this. The real prob-
lems come from the complexity involved in integrating different systems. In this
example, we were greatly assisted by having a monoculture—making Rails talk to
Rails is easier than, say, making a J2EE system talk to Rails.


However, the advantage of a RESTful architecture lies in its constraints. Agreeing on
RESTful principles narrows the universe of discourse—it pares down the space in
which two systems can disagree and still call themselves RESTful. And REST con-
strains architecture in a way that has been found to be applicable to most applica-
tions, so it is a reasonable default for new architectures. The conventions of
ActiveResource layer on top of these constraints in a way that is friendly to Rails/
ActiveRecord applications, and not very difficult to integrate with other applications.

Free download pdf