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.

Versioning an API<br />

last_response.body.should eql(body)<br />

projects = Nokogiri::XML(last_response.body)<br />

projects.css("project title").text.should eql("Ticketee")<br />

projects.css("project name").text.should eql("")<br />

end<br />

When you run this test using bin/rspec spec/api/v2/projects_spec.rb, it’s broken:<br />

Failure/Error: last_response.body.should eql(body)<br />

expected "[{[ticket hash without name key]}]"<br />

got "[{[ticket hash with name key]}]"<br />

This is because the name field is still being returned by your API. To exclude this field<br />

from your API, you can use the :except option to respond_with calls. In app/<br />

controllers/api/v2/projects_controller.rb the index method can now be altered to this:<br />

def index<br />

projects = Project.readable_by(current_user)<br />

respond_with(projects, :except => :name, :methods => :title)<br />

end<br />

The :except option here will exclude the name field from the responses provided by<br />

this API, and the methods option will call the title method (you’ll define it in a<br />

moment), providing that in your API response. You still need to have the name field in<br />

your database because it’s used in quite a few places in your application. You could<br />

change it all now, but this example is purely to show off the :except option and API<br />

versioning. A change like that would be recommended over this example, however it’s<br />

best left as another exercise for you.<br />

To make your API respond with the title method, you need to define it in app/<br />

models/project.rb inside the Project class like this:<br />

def title<br />

name<br />

end<br />

Now when you run bin/rspec spec/api/v2/projects_spec.rb, the tests that you<br />

edited will pass:<br />

8 examples, 0 failures<br />

You’ve seen how you can generate a new version of your API and alter the output of it,<br />

and the text says that your original API (v1) shouldn’t be effected, but was it? A great<br />

way to check is a quick run of bin/rspec spec/api/v1:<br />

15 examples, 0 failures<br />

Great, that’s all working! A quick run of rake spec will confirm your suspicions that<br />

nothing is broken:<br />

71 examples, 0 failures, 18 pending<br />

Awesome stuff. Let’s make a new commit:<br />

git add .<br />

git commit -m "Implement v2 of the API,<br />

383

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

Saved successfully!

Ooh no, something went wrong!