[ Pobierz całość w formacie PDF ]
.length.to_s29 }3031 [ status, headers, [body] ] Routing 3832 end33.34 end35 end36 end2.2.8 The Format SegmentLet s revisit the legacy default route again:1 match ':controller(/:action(/:id(.:format)))', via: :anyThe.:formatat the end matches a literal dot and a  format segment key after the id field.That means it willmatch, for example, a URL like:1 http://localhost:3000/products/show/3.jsonHere,params[:format]will be set tojson.The:formatfield is special; it has an effect inside the controlleraction.That effect is related to a method calledrespond_to.Therespond_tomethod allows you to write your action so that it will return different results, depending onthe requested format.Here s ashowaction for the products controller that offers either HTML or JSON:1 def show2 @product = Product.find(params[:id])3 respond_to do |format|4 format.html5 format.json { render json: @product.to_json }6 end7 endTherespond_toblock in this example has two clauses.The HTML clause just consists offormat.html.Arequest for HTML will be handled by the usual rendering of a view template.The JSON clause includes acode block; if JSON is requested, the block will be executed and the result of its execution will be returned tothe client.Here s a command-line illustration, usingcurl(slightly edited to reduce line noise): Routing 391 $ curl http://localhost:3000/products/show/1.json -i2 HTTP/1.1 200 OK3 Content-Type: application/json; charset=utf-84 Content-Length: 815 Connection: Keep-Alive67 {"created_at":"2013-02-09T18:25:03.513Z",8 "description":"Keyboard",9 "id":"1",10 "maker":"Apple",11 "updated_at":"2013-02-09T18:25:03.513Z"}The.jsonon the end of the URL results inrespond_tochoosing the json branch, and the returned documentis an JSON representation of the product.Requesting a format that is not included as an option in therespond_toblock will not generate an exception.Rails will return a406 Not Acceptablestatus, to indicate that it can t handle the request.If you want to setup an else condition for yourrespond_toblock, you can use theanymethod, which tellsRails to catch any other formats not explicitly defined.1 def show2 @product = Product.find(params[:id])3 respond_to do |format|4 format.html5 format.json { render json: @product.to_json }6 format.any7 end8 endJust make sure that you explicitly tellanywhat to do with the request or have view templates correspondingto the formats you expect.Otherwise, you ll get aMissingTemplateexception.1 ActionView::MissingTemplate (Missing template products/show,2 application/show with {:locale=>[:en], :formats=>[:xml],3 :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}.)2.2.9 Routes as Rack EndpointsYou ll see usage of the:tooption in routes throughout this chapter.What s most interesting about:tois thatits value is what s referred to as a Rack Endpoint.To illustrate, consider the following simple example:1 get "/hello", to: proc {|env| [200, {}, ["Hello world"]] }The router is very loosely coupled to controllers! The shorthand syntax (like"items#show") relies on theactionmethod of controller classes to return a Rack endpoint that executes the action requested. Routing 401 >> ItemsController.action(:show)2 => #The ability to dispatch to a Rack-based application, such as one created with Sinatra³, can be achieved using themountmethod.Themountmethod accepts an:atoption, which specifies the route the Rack-based applicationwill map to.1 class HelloApp '/hello'2.2.10 Accept HeaderYou can also trigger a branching onrespond_toby setting theAcceptheader in the request.When you do this,there s no need to add the.:formatpart of the URL.(However, note that out in the real world, it s difficultto get this technique to work reliably due to HTTP client/browser inconsistencies.)Here s acurlexample that does not specify an.jsonformat, but does set theAcceptheader toapplication/json:1 $ curl -i -H "Accept: application/json"2 http://localhost:3000/products/show/13 HTTP/1.1 200 OK4 Content-Type: application/json; charset=utf-85 Content-Length: 816 Connection: Keep-Alive78 {"created_at":"2013-02-09T18:25:03.513Z",9 "description":"Keyboard",10 "id":"1",11 "maker":"Apple",12 "updated_at":"2013-02-09T18:25:03.513Z"}The result is exactly the same as in the previous example.³http://www.sinatrarb.com Routing 412.2.11 Segment Key ConstraintsSometimes you want not only to recognize a route, but to recognize it at a finer-grained level than just whatcomponents or fields it has.You can do this through the use of the:constraintoption (and possibly regularexpressions).For example, you could route allshowrequests so that they went to an error action if theiridfields werenon-numerical.You d do this by creating two routes, one that handled numerical ids, and a fall-through routethat handled the rest:1 get ':controller/show/:id' => :show, constraints: {:id => /\d+/}2 get ':controller/show/:id' => :show_errorImplicit AnchoringThe example constraint we ve been using1 constraints: {:id => /\d+/}seems like it would match"foo32bar".It doesn t because Rails implicitly anchors it at both ends.In fact, as of this writing, adding explicit anchors\AandZcauses exceptions to be raised [ Pobierz caÅ‚ość w formacie PDF ]

  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • szamanka888.keep.pl