REST

Background and Theory

Rails Implementation of RESTCRUD

REST Building Blocks in Rails

map.resources :articles

Method URL Action Helper
GET /articles index articles_path
GET /articles/1 show article_path(:id => 1)
GET /articles/new new new_article_path
GET /articles/1/edit edit edit_article_path(:id => 1)
POST /articles create articles_path
PUT /articles update article_path(:id => 1)
DELETE /articles/1 destroy article_path(:id => 1)

REST Simplifies Links and Forms


# Without REST
link_to "Show", :controller => 'articles', :action => 'show', :id => @article
link_to "Destroy", :controller => 'articles', :action => 'destroy', :id => @article
form_for(@article, :url => { :action => "create" })

# With REST
link_to "Show", @article
link_to "Destroy", @article, :method => :delete
form_for(@article)

Custom Resource Routes


# Adding a new recent action for a collection
# GET /articles/recent (recent_articles_path)
map.resources :articles, :collection => { :recent => :get }

# Adding an action for an individual resource
# PUT /articles/1/release (release_article_path(:id => 1))
map.resources :articles, :member => { :release => :put }

Nested Resources (Associations)


map.resources :article, :has_one => :author, :has_many => [:comments, :attachments]

# Same as:
map.resources :articles do |article|
  article.resource  :author
  article.resources :comments
  article.resources :attachments
end

Scaffolding


script/generate scaffold article title:string body:text publish_time:datetime

Consuming REST


# You can any HTTP client to consume a REST service, such as curl or wget on the
# command line, or Net::HTTP in your Ruby scripts.
# Using the ActiveResource client:
class Post < ActiveResource::Base
  self.site = "http://localhost:3000" 
end

post = Post.find(1)
post.inspect
post.body = “new body”
post.save

Authentication


class PostsController < ApplicationController
  before_filter :authenticate

  private
  def authenticate
    authenticate_or_request_with_http_basic do |user_name, password|
      user_name == "peter" && password == "open sesame" 
    end
  end
end