Img source: railscarma.com

It is no doubt that there are certain pages that you do not need to have them viewed by all the visitors of your application. You can also have users of different roles that may not be allowed to access certain parts of your applications. There is a really good Ruby gem called cancan that excels at this. It makes the authorization of your app resources pretty straight-forward, so you do not have to duplicate permission checking code across controllers and views.

You can install it as other Ruby gems:

<span style="font-weight: 400;">gem ‘cancan’ </span>

After installing, you need to define user permissions in a special class called Ability. You can generate this class using a Rails 3 generator:

<span style="font-weight: 400;">rails g cancan:ability</span>

In this new class you need to define permissions. You can see this wiki page which clearly explains ways of defining them.

After defining your permissions, you can then use it in your views:

<span style="font-weight: 400;"><% if can? :update, @post %></span>
<span style="font-weight: 400;">  <%= link_to "Edit", edit_post_path(@post) %></span>
<span style="font-weight: 400;"><% end %></span>

You can authorize your controllers using authorize! method, which raises an exception when the permission is not fulfilled.

<span style="font-weight: 400;">def show</span>
<span style="font-weight: 400;">  @post = Post.find(params[:id])</span>
<span style="font-weight: 400;">  authorize! :read, @post</span>
<span style="font-weight: 400;">end</span>

You can read more about authorizing controller actions at the following wiki.

You can also throw errors when permissions are not met.

This Ruby gem is an open source project, MIT licensed and very famous on GitHub, where it has reached 6,229 stars until now. You can learn more about it at its GitHub page and of course free to go and see the code for yourself, and try to make your contributions to it.