27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Mounting a Rack application with Rails<br />

This is because you haven’t yet defined the module for the Api::V3 namespace. Let’s<br />

create a new file at app/controllers/api/v3/json/tickets.rb that defines this module, as<br />

shown in the following listing.<br />

Listing 18.8 app/controllers/api/v3/json/tickets.rb<br />

require 'sinatra'<br />

module Api<br />

module V3<br />

module JSON<br />

class Tickets < Sinatra::Base<br />

before do<br />

headers "Content-Type" => "text/json"<br />

end<br />

get '/' do<br />

[]<br />

end<br />

end<br />

end<br />

end<br />

end<br />

Within this file you define the Api::V3::JSON::Tickets class that is described at the<br />

top of your spec, which will now make your spec run. This class inherits from Sinatra::Base<br />

so that you’ll get the helpful methods that Sinatra provides, such as the<br />

before B and get methods that you use here. You’ve already seen what get can do,<br />

but before is new. This method is similar to a before_filter in Rails and will execute<br />

the block before each request. In this block, you set the headers for the request, using<br />

Sinatra’s headers method, so that your API identifies as sending back a text/json<br />

response.<br />

Let’s rerun it using bin/rspec spec/api/v3/json/tickets_spec.rb:<br />

Failure/Error: get url, :token => token<br />

ActionController::RoutingError:<br />

No route matches [GET] "/api/v3/json/projects/1/tickets"<br />

This is a better start: now your test is running and failing as it should because you<br />

haven’t defined the route for it yet. Your test is expecting to be able to do a GET<br />

request to /api/v3/json/projects/1/tickets but cannot.<br />

This route can be interpreted as /api/v3/json/projects/:project_id/tickets, and you<br />

can use the api namespace already in config/routes.rb to act as a home for this route.<br />

Let’s put some code for v3 of your API inside this namespace now:<br />

namespace :v3 do<br />

namespace :json do<br />

mount Api::V3::JSON::Tickets,<br />

:at => "/projects/:project_id/tickets"<br />

end<br />

end<br />

B Before method<br />

529

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!