27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Pagination<br />

If you click the 1 link or the Prev link, you’ll be taken back to the first page. All of<br />

that functionality was given to you by the paginate method in your views and the page<br />

call in your controller. You didn’t have to code any of this yourself, which is great.<br />

Next, we’ll look at how you can add this same kind of pagination to the tickets API.<br />

16.1.3 Paginating an API<br />

You’ve easily set up pagination for your tickets on the interface that a user sees, to ease<br />

the load on the database. However, for your tickets API you’re still returning all the<br />

tickets for a project when they’re requested, and therefore you’ll run into the same<br />

problems you solved in the previous section.<br />

Your API is different though. You can’t provide a pagination link for the tickets<br />

returned by an API. Instead, you’ll have to rely on people passing in a page number,<br />

which you’ll then use to return that page of tickets.<br />

To test this, you’re going to go into your API spec file for tickets at spec/api/v2/<br />

tickets_spec.rb and add another test. This one should assert that when you pass in a<br />

page parameter to your requests, you receive that page of tickets, rather than all of the<br />

tickets or a different page.<br />

In your API you’ll limit requests to 50 per response, but you may choose to set this<br />

a little higher. 4 Therefore, you’ll create 100 tickets, which should give you enough<br />

tickets to test that you can get the first and second pages of your API.<br />

You’ll add another context to spec/api/v2/tickets_spec.rb to test pagination, using<br />

the code shown in the following listing.<br />

Listing 16.3 spec/api/v2/tickets_spec.rb<br />

context "pagination" do<br />

before do<br />

100.times do<br />

Factory(:ticket, :project => project, :user => @user)<br />

end<br />

end<br />

it "gets the first page" do<br />

get "/api/v2/projects/#{project.id}/tickets.json",<br />

:token => token,<br />

:page => 1<br />

last_response.body.should eql(project.tickets.page(1).per(50).to_json)<br />

end<br />

it "gets the second page" do<br />

get "/api/v2/projects/#{project.id}/tickets.json?page=2",<br />

:token => token,<br />

:page => 2<br />

last_response.body.should eql(project.tickets.page(2).per(50).to_json)<br />

end<br />

end<br />

4 200 seems to be a common number to use for API return objects per request.<br />

443

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

Saved successfully!

Ooh no, something went wrong!