Computer Science and Engineering n The Ohio State University To Ponder (recall…) o GET, HEAD n Request: should be safe (no side effects) n Request has header only (no body) o PUT n Update (or create): should be idempotent o DELETE n Delete: should be idempotent o POST n Create (or update): changes server state n Beware re-sending! o HTTP does not enforce these semantics
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Computer Science and Engineering n The Ohio State University
To Ponder (recall…)
o GET, HEADn Request: should be safe (no side effects)n Request has header only (no body)
o PUTn Update (or create): should be idempotent
o DELETEn Delete: should be idempotent
o POSTn Create (or update): changes server staten Beware re-sending!
o HTTP does not enforce these semantics
Computer Science and Engineering n College of Engineering n The Ohio State University
Rails:Routes
Lecture 21
Computer Science and Engineering n The Ohio State University
Recall: Rails Architecture
Computer Science and Engineering n The Ohio State University
Configuration
o Need to map an HTTP request (verb, URL, parameters) to an application action (a method in a Ruby class)n Framework invokes the method, passing in
parameters from HTTP request as argumentsn Results in an HTTP response, typically with an
HTML payload, sent back to client's browsero These mappings are called routeso Defined in config/routes.rb
n Ruby code, but highly stylized (another DSL)n Checked top to bottom for first match
Computer Science and Engineering n The Ohio State University
Basic Routeo Pattern string + application action
n In config/routes.rbn Pattern string usually contains segments
o Example routeget 'status/go/:system/memory/:seg',
to: 'reporter#show'o Matches any HTTP request like
GET /status/go/lander/memory/0?page=3o Result:
n Instantiates ReporterControllern Invokes show method on that new instancen Provides an object called params (like a hash)params = { system: 'lander',
seg: '0',page: '3' }
Computer Science and Engineering n The Ohio State University
Default Valueso Special segments
n :controller - the controller class to usen :action - the method to invoke in that controller
o Example routeget ':controller/go/:action/:system'
o Matches any HTTP request likeGET /reporter/go/show/lander?page=3
o Result:n Instantiates ReporterControllern Invokes show method on that new instancen Provides an object called paramsparams = { system: 'lander',
page: '3',# also :controller and :action }
Computer Science and Engineering n The Ohio State University
Customizing Routes
o Recognize different HTTP verb(s)n get, put, post, deleten Alternative: match via: [:get, :post]
o Optional segments with ( )get ':controller(/:action(/:id))'
o Default values for paramsget 'photos/:id', to: 'photos#show',
defaults: { format: 'jpg' }
Computer Science and Engineering n The Ohio State University
REST
o REpresentational State Transfern An architectural style for web applicationsn Maps database operations to HTTP requests
o Small set of database operations (CRUD)n Create, Read, Update, Delete
o Small set of HTTP verbs, with fixed semantics (e.g., idempotence)n GET, POST, PUT, DELETE
o The protocol is statelesso Resource: bundle of (server-side) state
n Each resource is identified by a URL
Computer Science and Engineering n The Ohio State University
Resources
o A resource could be an individual membern Example: a single studentn Corresponds to a row in a table
o A resource could be a collection of itemsn Example: a set of studentsn Corresponds to a table
o In REST, resources have URLsn Each member element has its own URL
http://quickrosters.com/students/42
n Each collection has its own URLhttp://quickrosters.com/students
Computer Science and Engineering n The Ohio State University
Read Collection: GET
Request
GET /students HTTP/1.1Host: quickrosters.com
Computer Science and Engineering n The Ohio State University
Read Collection: GET
Request
GET /students HTTP/1.1Host: quickrosters.com
Computer Science and Engineering n The Ohio State University
Read Collection: GET
Computer Science and Engineering n The Ohio State University
HTML Source (GET Collection)…<h1>Students</h1><table><tr><th>Fname</th><th>Lname</th><th>Buckid</th><th colspan="3"></th>
</tr>…<tr><td>Primo</td><td>Carnera</td><td>334432</td><td><a href="/students/3">Show</a></td><td><a href="/students/3/edit">Edit</a></td><td><a href="/students/3" data-confirm="Are you sure?"
Computer Science and Engineering n The Ohio State University
Rails Resource-Based Routeso For a resource like :students, the action pack
includesn 1 controller (StudentsController)n 7 routes (each with a method in controller)n 4 Views (list of students, show 1 student, new, edit)
HTTPVerb
URL Resource Method Response(View)
GET /students Collection index list allPOST /students Collection create show oneGET /students/new Collection new blank formGET /students/3 Member show show oneGET /students/3/edit Member edit filled formPUT /students/3 Member update show oneDELETE /students/3 Member destroy list all
Computer Science and Engineering n The Ohio State University
Defining Resource-Based Routes
o In RosterTool app’s config/routes.rbRails.application.routes.draw do
resources :studentsresources :faculty
end
Computer Science and Engineering n The Ohio State University
Customizing Routeso To change which 7 routes are created
resources :students, except:[:update, :destroy]
resources :grades, only: [:index, :show]o To specify a particular controller
resources :students, controller: 'ugrads'o To rename certain actions
o To add more routes to standard setn Add GET /students/:id/avatar (i.e. on member)n Add GET /students/search (i.e. on collection)resources :students doget 'avatar', on: :memberget 'search', on: :collection
end
Computer Science and Engineering n The Ohio State University
Segment Keyso URL request has arguments for controller
n Example: products/42n Pattern string: 'products/:id'
o Segment key gets value when route matches
o Controller gets a hash (called params) of segment keys and their valuesn Example: params[:id] is '42'
o Common case: Look up an item by iddef set_product@product = Product.find(params[:id])
end
Computer Science and Engineering n The Ohio State University
Recognition vs Generationo Dual problems
n Recognize a URL (request for an action)n Generate a URL (a hyperlink or redirect)
o Routes used for both!o For generation, route must be named
get 'status/:seg', to: 'reporter#show',as: :info
o Results in two helpers (_path, _url)info_path(4)#=> "/status/4"info_url(4) #=> "http://faces.com/status/4"
o Used with link_to to generate hyperlinkslink_to 'S', info_path(4), class: 'btn'#=> "<a class='btn' href='/status/4'>S</a>"
Computer Science and Engineering n The Ohio State University
Helper Methods for Resourceso Resource-based routes have names
Computer Science and Engineering n The Ohio State University
Root Route
o With no matching route, GET for http://example.com gets index.html from application's public directory
o To customize landing page, 2 choices:n Create public/index.htmln Add root route to config/routes.rb,
pointing to a controller#action (better)root to: "welcome#index"
Computer Science and Engineering n The Ohio State University
Singleton Resourceso Declared with singular syntax
resource :systemo You get only 1 resource, not 2
n Controller still plural (e.g., SystemsController)n URLs are singular (e.g., /system/edit
o Only 6 standard routesn No index collection action to list membersn POST /system -> createn GET /system/new -> newn GET /system/edit -> editn GET /system -> shown PUT /system -> updaten DELETE /system -> destroy
Computer Science and Engineering n The Ohio State University
Summary
o REST and CRUDn Create, read, update, destroyn Map data to resourcesn Map actions to HTTP requests (verb +
URL)o Routes
n Connect HTTP request to specific method in a controller class
n Defined in config/routes.rbn Resource based, or match-basedn Dual problem: recognition and generation