Sonntag, 2. März 2014

REST in piece! ...a Ruby on Rails perspective

REST means Representational State Transfer and there is also a comprehensive REST dissertation.
This is just a short summary from the Ruby on Rails point of view.
Hence:
  1. A resource service is represented by an URL (Uniform Resource Locator) (e.g. /rails_app/people)
  2. The exact resource itself is represented by the URI (Uniform Resource Identifier) (e.g. /rails_app/people/1)
  3. HTTP verbs are used for addressing the operation (in Ruby on Rails only: GET, POST, PUT and DELETE)
  4. A resources operation can provide various documents (HTML, XML, JSON or others)
This could be a typical RESTful Rails controller, having the Rails standard actions (REST operations):
class PeopleController < ApplicationController
  # HTTP verb: GET
  def index
    respond_to do |format|
      format.html
      format.xml
    end
  end

  # HTTP verb: GET
  def show
    respond_to do |format|
      format.html
      format.json
    end
  end

  # HTTP verb: GET
  def new
    respond_to do |format|
      format.html
    end
  end

  # HTTP verb: GET
  def edit
    respond_to do |format|
      format.html
    end
  end

  # HTTP verb: POST
  def create
    respond_to do |format|
      format.html
    end
  end

  # HTTP verb: PUT
  def update
    respond_to do |format|
      format.js
    end
  end

  # HTTP verb: DELETE
  def destroy
    respond_to do |format|
      format.js
    end
  end
end
In that example the response documents vary from simple HTML to Javascript and were elaborated extensively by the ActionController#respond_to.
RESTful controllers and the pathes to their actions are well structured:
Path HTTP verb Action Behaviour
/people GET index Returns a collection of people
/people POST create Creates a new person
/people/new GET new Returns the form a new person
/people/1 GET show Displays the person having ID: 1
/people/1 PUT update Updates the person having ID: 1
/people/1 DELETE destroy Deletes the person having ID: 1
/people/1/edit GET edit Returns the form for editing the person having ID: 1
To be explicit: there are only a few cases, where your controllers should have other or more than those 7 actions. They already cover the resources lifecycle in terms of CRUD (Create Read Update Delete). And they never should behave different than the mentioned behaviour.
Create your Ruby on Rails controllers in a RESTful style!
It helps you to establish well structured interfaces depending on the path, the HTTP verb and the MIME type.

Supported by Ruby 1.9.3 and Ruby on Rails 3.2.1