Pundit is Minimal authorization through OO design and pure Ruby classes.
[code language=”ruby”] gem pundit[/code]
Include Pundit in your application controller:
[code language=”ruby”]
class ApplicationController < ActionController::Base
include Pundit
protect_from_forgery
end
[/code]
]
Optionally, you can run the generator, which will set up an application policy with some useful defaults for you:
[code language=”ruby”]rails g pundit:install[/code]
After generating your application policy, restart the Rails server so that Rails can pick up any classes in the new app/policies/ directory.
To restrict a page access based on role : for index action in article controller
if a page is only can be accessed by admin then add index? action to the pundit article class
and write the permission “user.admin?” // (user.admin? – code for return is the user is admin or not ) Admin only allowed to access this page
[code language=”ruby”]class ArticlePolicy
attr_reader :user, :article
def initialize(user,article)
@user = user
@article = article
end
def index?
user.admin?
end
end
[/code]