SlideShare a Scribd company logo
1 of 121
Download to read offline
REST & ActiveResource
      Matthijs Langenberg
Webservices
Wat zijn webservices
”The W3C defines a Web Service as a software system designed to support
     interoperable machine to machine interaction over a network.”
                             -- Wikipedia
Bevorder ‘machine to machine interaction’
HTML is moeilijk te parsen
Geef iets anders terug

        XML?
Just Another View
respond_to
class ArticlesController < ApplicationController
 def show
    @article = Article.find(params[:id])
    respond_to do |format|
      format.html
      format.xml { render :xml => @article }
    end
 end
end
Soorten Webservices

• Remote procedure calls (RPC)
• Service-oriented architecture (SOA)
• Representational state transfer (REST)
Rails votes REST
Rails votes REST

   BIG TIME!
Wat is REST?
REpresentional State Transfer
HTTP’s:
“convention over configuration”
Schreef geen vervanging voor iets wat HTTP je gratis geeft
HTTP Abuse
Wat is er mis met dit request?
  GET http://myblog.com/articles/destroy/1
HTTP Abuse
Wat is er mis met dit request?
  GET http://myblog.com/articles/destroy/1



                     Conflict
HTTP Abuse
Wat is er mis met dit request?
  GET http://myblog.com/articles/destroy/1



                     Conflict

• Actie staat in URL
• Uitgevoerd actie is in conflict met HTTP methode
The REST-way


DELETE http://myblog.com/articles/1
URI’s
URI’s

GET /articles/create

GET /articles/show/1

GET /articles/update/1

GET /articles/destroy/1
URI’s

GET /articles/create

GET /articles/show/1

GET /articles/update/1

GET /articles/destroy/1
Mapping
Mapping

HTTP

 GET

POST

 PUT

DELETE
Mapping

HTTP     Controller

 GET      SHOW

POST      CREATE

 PUT      UPDATE

DELETE   DESTROY
Resourceful URI’s
Resourceful URI’s

GET /articles

POST /articles/create

GET /articles/show/1

POST /articles/update/1

GET /articles/destroy/1
Resourceful URI’s

                          ➡   GET /articles
GET /articles

                          ➡   POST /articles
POST /articles/create

                          ➡   GET /articles/1
GET /articles/show/1

                          ➡   PUT /articles/1
POST /articles/update/1

                          ➡   DELETE /articles/1
GET /articles/destroy/1
Gratis named routes
ActionController::Routing::Routes.draw do |map|
  map.resources :articles do |articles|
    articles.resources :comments
  end
end
ActionController::Routing::Routes.draw do |map|
  map.resources :articles do |articles|
    articles.resources :comments
  end
end
ActionController::Routing::Routes.draw do |map|
     map.resources :articles do |articles|
       articles.resources :comments
     end
   end



articles_url
article_url
new_article_url
edit_article_url

article_comments_url
article_comment_url
article_new_comment_url
article_edit_comment_url
ActionController::Routing::Routes.draw do |map|
     map.resources :articles do |articles|
       articles.resources :comments
     end
   end



articles_url               ➡   /articles
article_url                ➡   /articles/:id
new_article_url            ➡   /articles/new
edit_article_url           ➡   /articles/:id/edit

article_comments_url       ➡   /articles/:article_id/comments
article_comment_url        ➡   /articles/:article_id/comments/:id
article_new_comment_url    ➡   /articles/:article_id/comments/new
article_edit_comment_url   ➡   /articles/:article_id/comments/:id/edit
link_to article.title,

 { 
:controller => ‘article’,
    
 :action => ‘show’,

 
 :id => article }
link_to article.title,

 { 
:controller => ‘article’,
    
 :action => ‘show’,

 
 :id => article }
link_to article.title,
     
 { 
:controller => ‘article’,
         
 :action => ‘show’,
     
 
 :id => article }




link_to article.title, article_url(article)
link_to article.title,
     
 { 
:controller => ‘article’,
         
 :action => ‘show’,
     
 
 :id => article }




link_to article.title, article_url(article)
link_to article.title, article
Wat zou je doen?
Je wilt comments aan articles toevoegen,
ArticlesController is aanwezig.
Wat zou je doen?
        Je wilt comments aan articles toevoegen,
        ArticlesController is aanwezig.


1) Voeg een actie ‘add_comment’ aan ArticlesController toe.
    (POST /articles/1/add_comment)
Wat zou je doen?
        Je wilt comments aan articles toevoegen,
        ArticlesController is aanwezig.


1) Voeg een actie ‘add_comment’ aan ArticlesController toe.
    (POST /articles/1/add_comment)

2) Maak een CommentsController, met een ‘create’ actie.
    (POST /comments/create?article_id=1)
Mr. RESTful zegt:
Mr. RESTful zegt:
     Antwoord 2
Mr. RESTful zegt:
                    Antwoord 2


• Een comment is een een aparte resource
Mr. RESTful zegt:
                   Antwoord 2


• Een comment is een een aparte resource
• Er bestaat geen ‘add_comment’ methode in HTTP
Mr. RESTful zegt:
                    Antwoord 2


• Een comment is een een aparte resource
• Er bestaat geen ‘add_comment’ methode in HTTP
• Er bestaat wel een ‘create’ (POST) methode in HTTP
Geen Namespaces!

•   POST /articles/create

•   POST /articles/create_comment

•   GET /articles/destroy

•   GET /articles/destroy_comment
Teveel vrijheid is niet goed
class ArticlesController < ApplicationController
 def show
   @article = Article.find(params[:id])
 end

 def show_rss
   @article = Article.find(params[:id])
   render :rss => @article.to_rss
 end

 def show_atom
   @article = Article.find(params[:id])
   render :atom => @article.to_atom
 end

 def show_xml
   @article = Article.find(params[:id])
   render :xml => @article.to_xml
 end

 def show_ajax
    @article = Article.find(params[:id])
    render :template => show_article.rjs
 end
end
Geen aparte actie voor alternatieve view!
class ArticlesController < ApplicationController
 def show
    @article = Article.find(params[:id])
    respond_to do |format|
      format.html
      format.rss { render :rss => @article.to_rss }
      format.atom { render :atom => @article.to_atom }
      format.xml { render :xml => @article.to_xml }
      format.rjs { render :template => ‘show_article.rjs’ }
    end
 end
end
Wauw!
HTTP method naar controller actie mapping actie klinkt tof!
Maar er zit een adder ...
Maar er zit een adder ...
Browsers ondersteunen PUT en DELETE niet!
Browsers ondersteunen PUT en DELETE niet!

<input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
Gelukkig zijn de helpers ook
       aangepast. ;-)
HTML_options


•   link_to “delete”, article_path(1), :method => ‘delete’

•   link_to_remote, “delete”, article_path(1), :method => ‘delete’

•   form_tag(member_path(2), :method => :put)
form_for
              remote_form_for
Bepalen op basis van AR object de method:
  form_for(Movie.new):

  <form action=quot;/moviesquot; class=quot;new_moviequot; id=quot;new_moviequot; method=quot;postquot;>




  form_for(Movie.find(:first)):

  <form action=quot;/movies/1quot; class=quot;edit_moviequot;
  id=quot;edit_movie_1quot; method=quot;postquot;>

  <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
Controller Acties
MoviesController#index
MoviesController#index
# GET /movies
# GET /movies.xml
def index
 @movies = Movie.find(:all)

 respond_to do |format|
  format.html # index.html.erb
  format.xml { render :xml => @movies }
 end
end
MoviesController#index
                                          <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
# GET /movies
                                          <movies>
# GET /movies.xml                          <movie>
def index                                   <director>Chris Miller</director>
 @movies = Movie.find(:all)                  <id type=quot;integerquot;>1</id>
                                            <rating type=quot;decimalquot;>7.0</rating>
 respond_to do |format|                     <title>Shrek the Third</title>
  format.html # index.html.erb             </movie>
                                           <movie>
  format.xml { render :xml => @movies }
                                            <director>Sam Raimi</director>
 end
                                            <id type=quot;integerquot;>2</id>
end
                                            <rating type=quot;decimalquot;>6.9</rating>
                                            <title>Spider-Man 3</title>
                                           </movie>
                                           <movie>
                                            <director>Juan Carlos Fresnadillo</director>
                                            <id type=quot;integerquot;>3</id>
                                            <rating type=quot;decimalquot;>7.7</rating>
                                            <title>28 Weeks Later</title>
                                           </movie>
                                          </movies>
MoviesController#show
MoviesController#show
# GET /movies/1
# GET /movies/1.xml
def show
 @movie = Movie.find(params[:id])

 respond_to do |format|
  format.html # show.html.erb
  format.xml { render :xml => @movie }
 end
end
MoviesController#show
# GET /movies/1                          <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
                                         <movie>
# GET /movies/1.xml
                                          <director>Chris Miller</director>
def show
                                          <id type=quot;integerquot;>1</id>
 @movie = Movie.find(params[:id])          <rating type=quot;decimalquot;>7.0</rating>
                                          <title>Shrek the Third</title>
 respond_to do |format|                  </movie>
  format.html # show.html.erb
  format.xml { render :xml => @movie }
 end
end
MoviesController#create
MoviesController#create
# POST /movies
# POST /movies.xml
def create
 @movie = Movie.new(params[:movie])

 respond_to do |format|
  if @movie.save
    flash[:notice] = 'Movie was successfully created.'
    format.html { redirect_to(@movie) }
    format.xml { render :xml => @movie,
        :status => :created,
        :location => @movie }
  else
    format.html { render :action => quot;newquot; }
    format.xml { render :xml => @movie.errors, :status => 422 }
  end
 end
end
MoviesController#create
                                                                  Status: 201 Created
                                                                  Location: http://localhost:3000/movies/16
# POST /movies
                                                                  <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
# POST /movies.xml
                                                                  <movie>
def create
                                                                   <director>Steven Spielbergh</director>
 @movie = Movie.new(params[:movie])
                                                                   <id type=quot;integerquot;>15</id>
                                                                   <rating type=quot;decimalquot;>8.3</rating>
 respond_to do |format|
                                                                   <title>Letters from Iwo Jima</title>
  if @movie.save
                                                                  </movie>
    flash[:notice] = 'Movie was successfully created.'
    format.html { redirect_to(@movie) }
    format.xml { render :xml => @movie,
        :status => :created,
        :location => @movie }
  else
    format.html { render :action => quot;newquot; }
    format.xml { render :xml => @movie.errors, :status => 422 }
  end
 end
end
MoviesController#create
                                                                  Status: 201 Created
                                                                  Location: http://localhost:3000/movies/16
# POST /movies
                                                                  <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
# POST /movies.xml
                                                                  <movie>
def create
                                                                   <director>Steven Spielbergh</director>
 @movie = Movie.new(params[:movie])
                                                                   <id type=quot;integerquot;>15</id>
                                                                   <rating type=quot;decimalquot;>8.3</rating>
 respond_to do |format|
                                                                   <title>Letters from Iwo Jima</title>
  if @movie.save
                                                                  </movie>
    flash[:notice] = 'Movie was successfully created.'
    format.html { redirect_to(@movie) }
    format.xml { render :xml => @movie,
        :status => :created,
                                                                  Status: 422 Unprocessable Entity
        :location => @movie }
                                                                  <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
  else
                                                                  <errors>
    format.html { render :action => quot;newquot; }
                                                                   <error>Rating can't be blank</error>
    format.xml { render :xml => @movie.errors, :status => 422 }
                                                                   <error>Director can't be blank</error>
  end
                                                                   <error>Title can't be blank</error>
 end
                                                                  </errors>
end
MoviesController#update
MoviesController#update
# PUT /movies/1
# PUT /movies/1.xml
def update
 @movie = Movie.find(params[:id])

 respond_to do |format|
  if @movie.update_attributes(params[:movie])
    flash[:notice] = 'Movie was successfully updated.'
    format.html { redirect_to(@movie) }
    format.xml { head :ok }
  else
    format.html { render :action => quot;editquot; }
    format.xml { render :xml => @movie.errors, :status => 422 }
  end
 end
end
MoviesController#update
                                                                  Status: 200 OK
# PUT /movies/1
# PUT /movies/1.xml
def update
 @movie = Movie.find(params[:id])

 respond_to do |format|
  if @movie.update_attributes(params[:movie])
    flash[:notice] = 'Movie was successfully updated.'
    format.html { redirect_to(@movie) }
    format.xml { head :ok }
  else
    format.html { render :action => quot;editquot; }
    format.xml { render :xml => @movie.errors, :status => 422 }
  end
 end
end
MoviesController#update
                                                                  Status: 200 OK
# PUT /movies/1
# PUT /movies/1.xml
def update
 @movie = Movie.find(params[:id])
                                                                  Status: 422 Unprocessable Entity
 respond_to do |format|
                                                                  <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
  if @movie.update_attributes(params[:movie])
                                                                  <errors>
    flash[:notice] = 'Movie was successfully updated.'
                                                                   <error>Title can't be blank</error>
    format.html { redirect_to(@movie) }
                                                                  </errors>
    format.xml { head :ok }
  else
    format.html { render :action => quot;editquot; }
    format.xml { render :xml => @movie.errors, :status => 422 }
  end
 end
end
MoviesController#destroy
MoviesController#destroy

# DELETE /movies/1
# DELETE /movies/1.xml
def destroy
 @movie = Movie.find(params[:id])
 @movie.destroy

 respond_to do |format|
  format.html { redirect_to(movies_url) }
  format.xml { head :ok }
 end
end
MoviesController#destroy

# DELETE /movies/1                          Status: 200 OK
# DELETE /movies/1.xml
def destroy
 @movie = Movie.find(params[:id])
 @movie.destroy

 respond_to do |format|
  format.html { redirect_to(movies_url) }
  format.xml { head :ok }
 end
end
Scaffolding
maar er is meer!
ActiveResource
ActiveResource


•   Object-oriented REST services

•   Transparent met een RESTful service (Rails) werken

•   Net als ActiveRecord, maar dan voor REST
Browser
Browser


      GET /movies.html


Controller
(RESTful)
Browser


       GET /movies.html


 Controller
 (RESTful)

        Movie.find(:all)


ActiveRecord
Browser


       GET /movies.html


 Controller
 (RESTful)

         Movie.find(:all)


ActiveRecord

       SELECT * FROM MOVIES


    DB
Browser     Browser


                 GET /movies.html


           Controller
           (RESTful)

                   Movie.find(:all)


          ActiveRecord

                 SELECT * FROM MOVIES


              DB
Browser                   Browser


      GET /movies.html          GET /movies.html


                          Controller
Controller
                          (RESTful)

                                  Movie.find(:all)


                         ActiveRecord

                                SELECT * FROM MOVIES


                             DB
Browser                   Browser


        GET /movies.html          GET /movies.html


                            Controller
  Controller
                            (RESTful)

        Movie.find(:all)             Movie.find(:all)


ActiveResource             ActiveRecord

                                  SELECT * FROM MOVIES


                               DB
Browser                                    Browser


        GET /movies.html                           GET /movies.html


                                             Controller
  Controller
                                             (RESTful)

        Movie.find(:all)                              Movie.find(:all)

                          GET /movies.xml
ActiveResource                              ActiveRecord

                                                   SELECT * FROM MOVIES


                                                DB
Configuratie
Werken met RESTful webservices
      (ActiveResource)
Create
Create
Read
Read
Update
Update
Destroy
Destroy
Wat doet ARes?
Wat doet ARes?

• Genereer URL
Wat doet ARes?

• Genereer URL
• Request URL (XML)
Wat doet ARes?

• Genereer URL
• Request URL (XML)
• Verwerk request (XML)
Wat doet ARes?

• Genereer URL
• Request URL (XML)
• Verwerk request (XML)
• Biedt ActiveRecord-like API
Demo
Demo

1) RESTful Rails applicatie (met curl)
Demo

1) RESTful Rails applicatie (met curl)
2) Rails applicatie met ActiveResource
Demo

1) RESTful Rails applicatie (met curl)
2) Rails applicatie met ActiveResource
3) ActiveResource gem
Vragen?

 <mlangenberg@gmail.com>
#rubyenrails at irc.freenode.org

More Related Content

What's hot

Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorialClaude Tech
 
Django Templates
Django TemplatesDjango Templates
Django TemplatesWilly Liu
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based ViewsWilly Liu
 
Ionic tabs template explained
Ionic tabs template explainedIonic tabs template explained
Ionic tabs template explainedRamesh BN
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...Ho Chi Minh City Software Testing Club
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
Associations & JavaScript
Associations & JavaScriptAssociations & JavaScript
Associations & JavaScriptJoost Elfering
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Django の認証処理実装パターン / Django Authentication Patterns
Django の認証処理実装パターン / Django Authentication PatternsDjango の認証処理実装パターン / Django Authentication Patterns
Django の認証処理実装パターン / Django Authentication PatternsMasashi Shibata
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django AdminLincoln Loop
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in RailsSeungkyun Nam
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxWen-Tien Chang
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Chris Alfano
 
Story Driven Development With Cucumber
Story Driven Development With CucumberStory Driven Development With Cucumber
Story Driven Development With CucumberSean Cribbs
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginnersSpin Lai
 
PLAT-14 Forms Config, Customization, and Extension
PLAT-14 Forms Config, Customization, and ExtensionPLAT-14 Forms Config, Customization, and Extension
PLAT-14 Forms Config, Customization, and ExtensionAlfresco Software
 

What's hot (20)

Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
Django Templates
Django TemplatesDjango Templates
Django Templates
 
Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based Views
 
The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Ionic tabs template explained
Ionic tabs template explainedIonic tabs template explained
Ionic tabs template explained
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
Associations & JavaScript
Associations & JavaScriptAssociations & JavaScript
Associations & JavaScript
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
Django の認証処理実装パターン / Django Authentication Patterns
Django の認証処理実装パターン / Django Authentication PatternsDjango の認証処理実装パターン / Django Authentication Patterns
Django の認証処理実装パターン / Django Authentication Patterns
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django Admin
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in Rails
 
Jquery ui
Jquery uiJquery ui
Jquery ui
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 Ajax
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
 
Story Driven Development With Cucumber
Story Driven Development With CucumberStory Driven Development With Cucumber
Story Driven Development With Cucumber
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginners
 
PLAT-14 Forms Config, Customization, and Extension
PLAT-14 Forms Config, Customization, and ExtensionPLAT-14 Forms Config, Customization, and Extension
PLAT-14 Forms Config, Customization, and Extension
 

Similar to ActiveResource & REST

Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Michelangelo van Dam
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2A.K.M. Ahsrafuzzaman
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Magento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowMagento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowVrann Tulika
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful RailsViget Labs
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful RailsBen Scofield
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2Rory Gianni
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
"Full Stack frameworks or a story about how to reconcile Front (good) and Bac...
"Full Stack frameworks or a story about how to reconcile Front (good) and Bac..."Full Stack frameworks or a story about how to reconcile Front (good) and Bac...
"Full Stack frameworks or a story about how to reconcile Front (good) and Bac...Fwdays
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Joao Lucas Santana
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2RORLAB
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.jsTechExeter
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Plataformatec
 

Similar to ActiveResource & REST (20)

Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Redmine Betabeers SVQ
Redmine Betabeers SVQRedmine Betabeers SVQ
Redmine Betabeers SVQ
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
 
Rails <form> Chronicle
Rails <form> ChronicleRails <form> Chronicle
Rails <form> Chronicle
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Magento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowMagento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request Flow
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful Rails
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful Rails
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
"Full Stack frameworks or a story about how to reconcile Front (good) and Bac...
"Full Stack frameworks or a story about how to reconcile Front (good) and Bac..."Full Stack frameworks or a story about how to reconcile Front (good) and Bac...
"Full Stack frameworks or a story about how to reconcile Front (good) and Bac...
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 

More from Robbert

BDD & Rspec
BDD & Rspec BDD & Rspec
BDD & Rspec Robbert
 
A Ct Os Story
A Ct Os StoryA Ct Os Story
A Ct Os StoryRobbert
 
Camping For The Rest Of Us
Camping For The Rest Of UsCamping For The Rest Of Us
Camping For The Rest Of UsRobbert
 
Betty Builder, Een GUI voor het maken en aanpassen van Rails models en migra...
Betty Builder,  Een GUI voor het maken en aanpassen van Rails models en migra...Betty Builder,  Een GUI voor het maken en aanpassen van Rails models en migra...
Betty Builder, Een GUI voor het maken en aanpassen van Rails models en migra...Robbert
 
JRuby Rules
JRuby RulesJRuby Rules
JRuby RulesRobbert
 
Ruby Meets Cocoa
Ruby Meets CocoaRuby Meets Cocoa
Ruby Meets CocoaRobbert
 
Serving Up Your Rails App On A Mongrel Cluster
Serving Up Your Rails App On A Mongrel ClusterServing Up Your Rails App On A Mongrel Cluster
Serving Up Your Rails App On A Mongrel ClusterRobbert
 

More from Robbert (7)

BDD & Rspec
BDD & Rspec BDD & Rspec
BDD & Rspec
 
A Ct Os Story
A Ct Os StoryA Ct Os Story
A Ct Os Story
 
Camping For The Rest Of Us
Camping For The Rest Of UsCamping For The Rest Of Us
Camping For The Rest Of Us
 
Betty Builder, Een GUI voor het maken en aanpassen van Rails models en migra...
Betty Builder,  Een GUI voor het maken en aanpassen van Rails models en migra...Betty Builder,  Een GUI voor het maken en aanpassen van Rails models en migra...
Betty Builder, Een GUI voor het maken en aanpassen van Rails models en migra...
 
JRuby Rules
JRuby RulesJRuby Rules
JRuby Rules
 
Ruby Meets Cocoa
Ruby Meets CocoaRuby Meets Cocoa
Ruby Meets Cocoa
 
Serving Up Your Rails App On A Mongrel Cluster
Serving Up Your Rails App On A Mongrel ClusterServing Up Your Rails App On A Mongrel Cluster
Serving Up Your Rails App On A Mongrel Cluster
 

Recently uploaded

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

ActiveResource & REST

  • 1. REST & ActiveResource Matthijs Langenberg
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 10. ”The W3C defines a Web Service as a software system designed to support interoperable machine to machine interaction over a network.” -- Wikipedia
  • 11. Bevorder ‘machine to machine interaction’
  • 12. HTML is moeilijk te parsen
  • 13. Geef iets anders terug XML?
  • 16. class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) respond_to do |format| format.html format.xml { render :xml => @article } end end end
  • 17. Soorten Webservices • Remote procedure calls (RPC) • Service-oriented architecture (SOA) • Representational state transfer (REST)
  • 19. Rails votes REST BIG TIME!
  • 21.
  • 22.
  • 23.
  • 26. Schreef geen vervanging voor iets wat HTTP je gratis geeft
  • 27. HTTP Abuse Wat is er mis met dit request? GET http://myblog.com/articles/destroy/1
  • 28. HTTP Abuse Wat is er mis met dit request? GET http://myblog.com/articles/destroy/1 Conflict
  • 29. HTTP Abuse Wat is er mis met dit request? GET http://myblog.com/articles/destroy/1 Conflict • Actie staat in URL • Uitgevoerd actie is in conflict met HTTP methode
  • 32. URI’s GET /articles/create GET /articles/show/1 GET /articles/update/1 GET /articles/destroy/1
  • 33. URI’s GET /articles/create GET /articles/show/1 GET /articles/update/1 GET /articles/destroy/1
  • 36. Mapping HTTP Controller GET SHOW POST CREATE PUT UPDATE DELETE DESTROY
  • 38. Resourceful URI’s GET /articles POST /articles/create GET /articles/show/1 POST /articles/update/1 GET /articles/destroy/1
  • 39. Resourceful URI’s ➡ GET /articles GET /articles ➡ POST /articles POST /articles/create ➡ GET /articles/1 GET /articles/show/1 ➡ PUT /articles/1 POST /articles/update/1 ➡ DELETE /articles/1 GET /articles/destroy/1
  • 41.
  • 42. ActionController::Routing::Routes.draw do |map| map.resources :articles do |articles| articles.resources :comments end end
  • 43. ActionController::Routing::Routes.draw do |map| map.resources :articles do |articles| articles.resources :comments end end
  • 44. ActionController::Routing::Routes.draw do |map| map.resources :articles do |articles| articles.resources :comments end end articles_url article_url new_article_url edit_article_url article_comments_url article_comment_url article_new_comment_url article_edit_comment_url
  • 45. ActionController::Routing::Routes.draw do |map| map.resources :articles do |articles| articles.resources :comments end end articles_url ➡ /articles article_url ➡ /articles/:id new_article_url ➡ /articles/new edit_article_url ➡ /articles/:id/edit article_comments_url ➡ /articles/:article_id/comments article_comment_url ➡ /articles/:article_id/comments/:id article_new_comment_url ➡ /articles/:article_id/comments/new article_edit_comment_url ➡ /articles/:article_id/comments/:id/edit
  • 46.
  • 47. link_to article.title, { :controller => ‘article’, :action => ‘show’, :id => article }
  • 48. link_to article.title, { :controller => ‘article’, :action => ‘show’, :id => article }
  • 49. link_to article.title, { :controller => ‘article’, :action => ‘show’, :id => article } link_to article.title, article_url(article)
  • 50. link_to article.title, { :controller => ‘article’, :action => ‘show’, :id => article } link_to article.title, article_url(article) link_to article.title, article
  • 51. Wat zou je doen? Je wilt comments aan articles toevoegen, ArticlesController is aanwezig.
  • 52. Wat zou je doen? Je wilt comments aan articles toevoegen, ArticlesController is aanwezig. 1) Voeg een actie ‘add_comment’ aan ArticlesController toe. (POST /articles/1/add_comment)
  • 53. Wat zou je doen? Je wilt comments aan articles toevoegen, ArticlesController is aanwezig. 1) Voeg een actie ‘add_comment’ aan ArticlesController toe. (POST /articles/1/add_comment) 2) Maak een CommentsController, met een ‘create’ actie. (POST /comments/create?article_id=1)
  • 55. Mr. RESTful zegt: Antwoord 2
  • 56. Mr. RESTful zegt: Antwoord 2 • Een comment is een een aparte resource
  • 57. Mr. RESTful zegt: Antwoord 2 • Een comment is een een aparte resource • Er bestaat geen ‘add_comment’ methode in HTTP
  • 58. Mr. RESTful zegt: Antwoord 2 • Een comment is een een aparte resource • Er bestaat geen ‘add_comment’ methode in HTTP • Er bestaat wel een ‘create’ (POST) methode in HTTP
  • 59. Geen Namespaces! • POST /articles/create • POST /articles/create_comment • GET /articles/destroy • GET /articles/destroy_comment
  • 60. Teveel vrijheid is niet goed
  • 61. class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) end def show_rss @article = Article.find(params[:id]) render :rss => @article.to_rss end def show_atom @article = Article.find(params[:id]) render :atom => @article.to_atom end def show_xml @article = Article.find(params[:id]) render :xml => @article.to_xml end def show_ajax @article = Article.find(params[:id]) render :template => show_article.rjs end end
  • 62. Geen aparte actie voor alternatieve view!
  • 63. class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) respond_to do |format| format.html format.rss { render :rss => @article.to_rss } format.atom { render :atom => @article.to_atom } format.xml { render :xml => @article.to_xml } format.rjs { render :template => ‘show_article.rjs’ } end end end
  • 64. Wauw! HTTP method naar controller actie mapping actie klinkt tof!
  • 65. Maar er zit een adder ...
  • 66. Maar er zit een adder ...
  • 67. Browsers ondersteunen PUT en DELETE niet!
  • 68. Browsers ondersteunen PUT en DELETE niet! <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
  • 69. Gelukkig zijn de helpers ook aangepast. ;-)
  • 70. HTML_options • link_to “delete”, article_path(1), :method => ‘delete’ • link_to_remote, “delete”, article_path(1), :method => ‘delete’ • form_tag(member_path(2), :method => :put)
  • 71. form_for remote_form_for Bepalen op basis van AR object de method: form_for(Movie.new): <form action=quot;/moviesquot; class=quot;new_moviequot; id=quot;new_moviequot; method=quot;postquot;> form_for(Movie.find(:first)): <form action=quot;/movies/1quot; class=quot;edit_moviequot; id=quot;edit_movie_1quot; method=quot;postquot;> <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
  • 74. MoviesController#index # GET /movies # GET /movies.xml def index @movies = Movie.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @movies } end end
  • 75. MoviesController#index <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> # GET /movies <movies> # GET /movies.xml <movie> def index <director>Chris Miller</director> @movies = Movie.find(:all) <id type=quot;integerquot;>1</id> <rating type=quot;decimalquot;>7.0</rating> respond_to do |format| <title>Shrek the Third</title> format.html # index.html.erb </movie> <movie> format.xml { render :xml => @movies } <director>Sam Raimi</director> end <id type=quot;integerquot;>2</id> end <rating type=quot;decimalquot;>6.9</rating> <title>Spider-Man 3</title> </movie> <movie> <director>Juan Carlos Fresnadillo</director> <id type=quot;integerquot;>3</id> <rating type=quot;decimalquot;>7.7</rating> <title>28 Weeks Later</title> </movie> </movies>
  • 77. MoviesController#show # GET /movies/1 # GET /movies/1.xml def show @movie = Movie.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @movie } end end
  • 78. MoviesController#show # GET /movies/1 <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> <movie> # GET /movies/1.xml <director>Chris Miller</director> def show <id type=quot;integerquot;>1</id> @movie = Movie.find(params[:id]) <rating type=quot;decimalquot;>7.0</rating> <title>Shrek the Third</title> respond_to do |format| </movie> format.html # show.html.erb format.xml { render :xml => @movie } end end
  • 80. MoviesController#create # POST /movies # POST /movies.xml def create @movie = Movie.new(params[:movie]) respond_to do |format| if @movie.save flash[:notice] = 'Movie was successfully created.' format.html { redirect_to(@movie) } format.xml { render :xml => @movie, :status => :created, :location => @movie } else format.html { render :action => quot;newquot; } format.xml { render :xml => @movie.errors, :status => 422 } end end end
  • 81. MoviesController#create Status: 201 Created Location: http://localhost:3000/movies/16 # POST /movies <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> # POST /movies.xml <movie> def create <director>Steven Spielbergh</director> @movie = Movie.new(params[:movie]) <id type=quot;integerquot;>15</id> <rating type=quot;decimalquot;>8.3</rating> respond_to do |format| <title>Letters from Iwo Jima</title> if @movie.save </movie> flash[:notice] = 'Movie was successfully created.' format.html { redirect_to(@movie) } format.xml { render :xml => @movie, :status => :created, :location => @movie } else format.html { render :action => quot;newquot; } format.xml { render :xml => @movie.errors, :status => 422 } end end end
  • 82. MoviesController#create Status: 201 Created Location: http://localhost:3000/movies/16 # POST /movies <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> # POST /movies.xml <movie> def create <director>Steven Spielbergh</director> @movie = Movie.new(params[:movie]) <id type=quot;integerquot;>15</id> <rating type=quot;decimalquot;>8.3</rating> respond_to do |format| <title>Letters from Iwo Jima</title> if @movie.save </movie> flash[:notice] = 'Movie was successfully created.' format.html { redirect_to(@movie) } format.xml { render :xml => @movie, :status => :created, Status: 422 Unprocessable Entity :location => @movie } <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> else <errors> format.html { render :action => quot;newquot; } <error>Rating can't be blank</error> format.xml { render :xml => @movie.errors, :status => 422 } <error>Director can't be blank</error> end <error>Title can't be blank</error> end </errors> end
  • 84. MoviesController#update # PUT /movies/1 # PUT /movies/1.xml def update @movie = Movie.find(params[:id]) respond_to do |format| if @movie.update_attributes(params[:movie]) flash[:notice] = 'Movie was successfully updated.' format.html { redirect_to(@movie) } format.xml { head :ok } else format.html { render :action => quot;editquot; } format.xml { render :xml => @movie.errors, :status => 422 } end end end
  • 85. MoviesController#update Status: 200 OK # PUT /movies/1 # PUT /movies/1.xml def update @movie = Movie.find(params[:id]) respond_to do |format| if @movie.update_attributes(params[:movie]) flash[:notice] = 'Movie was successfully updated.' format.html { redirect_to(@movie) } format.xml { head :ok } else format.html { render :action => quot;editquot; } format.xml { render :xml => @movie.errors, :status => 422 } end end end
  • 86. MoviesController#update Status: 200 OK # PUT /movies/1 # PUT /movies/1.xml def update @movie = Movie.find(params[:id]) Status: 422 Unprocessable Entity respond_to do |format| <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> if @movie.update_attributes(params[:movie]) <errors> flash[:notice] = 'Movie was successfully updated.' <error>Title can't be blank</error> format.html { redirect_to(@movie) } </errors> format.xml { head :ok } else format.html { render :action => quot;editquot; } format.xml { render :xml => @movie.errors, :status => 422 } end end end
  • 88. MoviesController#destroy # DELETE /movies/1 # DELETE /movies/1.xml def destroy @movie = Movie.find(params[:id]) @movie.destroy respond_to do |format| format.html { redirect_to(movies_url) } format.xml { head :ok } end end
  • 89. MoviesController#destroy # DELETE /movies/1 Status: 200 OK # DELETE /movies/1.xml def destroy @movie = Movie.find(params[:id]) @movie.destroy respond_to do |format| format.html { redirect_to(movies_url) } format.xml { head :ok } end end
  • 91. maar er is meer!
  • 93. ActiveResource • Object-oriented REST services • Transparent met een RESTful service (Rails) werken • Net als ActiveRecord, maar dan voor REST
  • 95. Browser GET /movies.html Controller (RESTful)
  • 96. Browser GET /movies.html Controller (RESTful) Movie.find(:all) ActiveRecord
  • 97. Browser GET /movies.html Controller (RESTful) Movie.find(:all) ActiveRecord SELECT * FROM MOVIES DB
  • 98. Browser Browser GET /movies.html Controller (RESTful) Movie.find(:all) ActiveRecord SELECT * FROM MOVIES DB
  • 99. Browser Browser GET /movies.html GET /movies.html Controller Controller (RESTful) Movie.find(:all) ActiveRecord SELECT * FROM MOVIES DB
  • 100. Browser Browser GET /movies.html GET /movies.html Controller Controller (RESTful) Movie.find(:all) Movie.find(:all) ActiveResource ActiveRecord SELECT * FROM MOVIES DB
  • 101. Browser Browser GET /movies.html GET /movies.html Controller Controller (RESTful) Movie.find(:all) Movie.find(:all) GET /movies.xml ActiveResource ActiveRecord SELECT * FROM MOVIES DB
  • 103. Werken met RESTful webservices (ActiveResource)
  • 104. Create
  • 105. Create
  • 106. Read
  • 107. Read
  • 108. Update
  • 109. Update
  • 113. Wat doet ARes? • Genereer URL
  • 114. Wat doet ARes? • Genereer URL • Request URL (XML)
  • 115. Wat doet ARes? • Genereer URL • Request URL (XML) • Verwerk request (XML)
  • 116. Wat doet ARes? • Genereer URL • Request URL (XML) • Verwerk request (XML) • Biedt ActiveRecord-like API
  • 117. Demo
  • 118. Demo 1) RESTful Rails applicatie (met curl)
  • 119. Demo 1) RESTful Rails applicatie (met curl) 2) Rails applicatie met ActiveResource
  • 120. Demo 1) RESTful Rails applicatie (met curl) 2) Rails applicatie met ActiveResource 3) ActiveResource gem