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.

376 CHAPTER 13 Designing an API<br />

Listing 13.23 app/controllers/api/v1/tickets_controller.rb<br />

class Api::V1::TicketsController < Api::V1::BaseController<br />

before_filter :find_project<br />

private<br />

def find_project<br />

@project = Project.for(current_user).find(params[:project_id])<br />

rescue ActiveRecord::RecordNotFound<br />

error = { :error => "The project you were looking for" +<br />

" could not be found."}<br />

respond_with(error, :status => 404)<br />

end<br />

end<br />

In the beginning, you set up the controller to inherit from Api::V1::BaseController<br />

so that it inherits the basic behavior of your API. Then you tell it that this controller<br />

responds to both JSON and XML. Finally, you define a before_filter :find_project<br />

that will find a project, providing that the user is able to access it. If the user cannot<br />

access it, then you respond_with a 404 error.<br />

Underneath the before_filter in this controller, you need to define the index<br />

action to return a list of tickets for your project. You can do that with the code shown<br />

in the following listing.<br />

Listing 13.24 app/controllers/api/v1/tickets_controller.rb<br />

def index<br />

respond_with(@project.tickets)<br />

end<br />

That feels like you’re getting too much for free, doesn’t it? Rails is handling a lot of the<br />

actions here for you. When you run bin/rspec spec/api/v1/tickets_spec.rb specs<br />

again, your tests will now pass because you’ve got the controller defined correctly:<br />

2 examples, 0 failures<br />

This is a great start to generating a tickets API, and now with the skills you’ve learned<br />

a little earlier in this chapter you should be able to bash out the rest with little effort.<br />

Rather than covering that old ground again, it’ll be left as an exercise for you.<br />

Let’s run all the tests with rake spec to make sure you didn’t break anything:<br />

54 examples, 0 failures, 19 pending<br />

Nope, nothing broken there, which is awesome to see. Time for a commit:<br />

git add .<br />

git commit -m "Added beginnings of the V1 Tickets API"<br />

git push<br />

You should probably limit the number of tickets that are sent back through the API or,<br />

even better, cache the result. You’ll see ways to do both of these things in chapter 15,<br />

and then you can apply them to the API when you feel it’s right. For now, it would be

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

Saved successfully!

Ooh no, something went wrong!