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.

150 CHAPTER 7 Basic access control<br />

them: what would normally be users_path becomes admin_users_path, and new<br />

_user_path becomes new_admin_user_path.<br />

With this namespace defined, when you run bin/rspec spec/controllers/admin<br />

/users_controller_spec.rb, you should see it fail with a different error:<br />

Failure/Error: response.should redirect_to(root_path)<br />

Expected response to be a , but was <br />

This error appears because you need to implement the authorize_admin<br />

!before_filter for your namespace. To apply it to all controllers in this namespace,<br />

you create a new supercontroller whose only job (for now) is to call the before_filter.<br />

You can also put methods that are common to the admin section here.<br />

Create a new file at app/controllers/admin/base_controller.rb, and fill it with this<br />

code:<br />

class Admin::BaseController < ApplicationController<br />

before_filter :authorize_admin!<br />

end<br />

This file can double as an eventual homepage for the admin namespace and as a class<br />

that the other controllers inside the admin namespace can inherit from, which you’ll<br />

see in a moment. You inherit from ApplicationController with this controller so you<br />

receive all the benefits it provides, like the authorize_admin! method and the Action<br />

Controller functionality.<br />

Open app/controllers/admin/users_controller.rb, and change the first line of the<br />

controller from this<br />

class Admin::UsersController < ApplicationController<br />

to this:<br />

class Admin::UsersController < Admin::BaseController<br />

Because Admin::UsersController inherits from Admin::BaseController, the<br />

before_filter from Admin::BaseController now runs for every action inside<br />

Admin::UsersController, and therefore in your spec, should pass.<br />

Run it with bin/rspec spec/controllers/admin/users_controller_spec.rb<br />

now, and you should see this:<br />

.<br />

1 example, 0 failures<br />

With that done, you should ensure that everything is working as expected by running<br />

rake cucumber:ok spec:<br />

25 scenarios (25 passed)<br />

200 steps (200 passed)<br />

# and<br />

14 examples, 0 failures, 7 pending<br />

Great, everything is still green! Let’s commit that:

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

Saved successfully!

Ooh no, something went wrong!