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.

146 CHAPTER 7 Basic access control<br />

<br />

<br />

<br />

You’ll define the admins_only method soon, and it’ll take a block. Inside this block,<br />

you specify all the content you want shown if the user is an admin. No content will be<br />

shown if the user is not an admin. To define the admins_only helper, open app/helpers<br />

/application_helper.rb and define the method inside the module using this code:<br />

def admins_only(&block)<br />

block.call if current_user.try(:admin?)<br />

nil<br />

end<br />

The admins_only method takes a block, which is the code between the do and end in<br />

your view. To run this code inside the method, call block.call, which runs the specified<br />

block but only if current_user.try(:admin?) returns a value that evaluates to<br />

true. This try method tries a method on an object, and if that method doesn’t exist<br />

(as it wouldn’t if current_user were nil), then it returns nil. At the end of the<br />

method, you return nil so the content doesn’t show again.<br />

When you run this feature using bin/cucumber features/hidden_links.feature,<br />

it passes:<br />

3 scenarios (3 passed)<br />

12 steps (12 passed)<br />

Now that you’ve got the New Project link hiding if the user isn’t an admin, let’s do the<br />

same thing for the Edit Project and Delete Project links.<br />

7.3.3 Hiding the edit and delete links<br />

Add this admins_only helper to the Edit Project and Delete Project links on the projects<br />

show view, but not before adding further scenarios to cover these links to features/<br />

hidden_links.feature, as shown in the following listing.<br />

Listing 7.14 features/hidden_links.feature<br />

Scenario: Edit project link is hidden for non-signed-in users<br />

Given I am on the homepage<br />

When I follow "TextMate 2"<br />

Then I should not see the "Edit Project" link<br />

Scenario: Edit project link is hidden for signed-in users<br />

Given I am signed in as "user@ticketee.com"<br />

When I follow "TextMate 2"<br />

Then I should not see the "Edit Project" link<br />

Scenario: Edit project link is shown to admins<br />

Given I am signed in as "admin@ticketee.com"<br />

When I follow "TextMate 2"<br />

Then I should see the "Edit Project" link

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

Saved successfully!

Ooh no, something went wrong!