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.

380 CHAPTER 13 Designing an API<br />

13.3.3 Back to zero<br />

15 Not really.<br />

You need to reset the request_count of each user who’s made a request to your API.<br />

This will be a method on the User model, and so you’ll put its test in a new file as<br />

spec/models/user_spec.rb file, inside the describe User block, using the code from<br />

the following listing.<br />

Listing 13.28 spec/models/user_spec.rb<br />

require 'spec_helper'<br />

describe User do<br />

it "resets user request count" do<br />

user = Factory(:user)<br />

user.update_attribute(:request_count, 42)<br />

User.reset_request_count!<br />

user.reload<br />

user.request_count.should eql(0)<br />

end<br />

end<br />

With this spec, you set a new user’s request count to something other than 0; 42 is a<br />

random number, 15 and you’re quite fortunate for it to exist so that you can use it. The<br />

reset_request_count! method isn’t defined, but as the remainder of the test implies,<br />

the user’s request count should be 0. This test, unsurprisingly, will not pass when it<br />

runs, and so you should write the method to make it pass.<br />

As the reset_request_count! method is called on User, you define this method in<br />

app/models/user.rb using the following code above the to_s method:<br />

def self.reset_request_count!<br />

update_all("request_count = 0", "request_count > 0")<br />

end<br />

You’re placing this code right above the to_s method because it is best practice to<br />

place class methods (such as reset_request_count!) above instance methods in a<br />

model, as some instance methods may refer to class methods. Also, if everybody puts<br />

their code in logical places, then you won’t be confused when you look at it, which is<br />

what Rails is all about.<br />

The update_all method here will set the request_count on all user records (the<br />

first argument) that have a request_count > 0 (the second argument), or a request<br />

_count greater than zero. No point resetting counts that are zero back to zero.<br />

Now that the reset_request_count! method is defined, does it work as your test<br />

says it should? Well, let’s run bin/rspec spec/models/user_spec.rb:<br />

1 example, 0 failures<br />

Cool, so now you’ve got the request count being reset for all users whenever this<br />

method is called. You’ll take a look at calling this method automatically when we look<br />

at background jobs in chapter 15.

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

Saved successfully!

Ooh no, something went wrong!