Skip to content
Authorization framework for Ruby/Rails applications
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github [ci skip] Add issue and PR templates Apr 20, 2018
benchmarks rubocop: use standard-based config Mar 4, 2019
bin
docs fix examplary Post{s,}Controller, mention singularity Mar 19, 2019
gemfiles travis: add rails 6 Mar 4, 2019
lib
spec
test feat: add .with_target to scope matchers Mar 14, 2019
.gitattributes
.gitignore
.rubocop.yml feat: add .with_target to scope matchers Mar 14, 2019
.travis.yml
CHANGELOG.md
Gemfile
LICENSE.txt Update copyright notice to 2019 [ci skip] Feb 17, 2019
README.md [ci skip] Add features highlights to the docs Jul 4, 2018
Rakefile Add testing utils Apr 3, 2018
action_policy.gemspec rubocop: use standard-based config Mar 4, 2019

README.md

Gem Version Build Status Documentation

ActionPolicy

Action Policy is an authorization framework for Ruby and Rails applications.

📑 Documentation

Sponsored by Evil Martians

Resources

Installation

Add this line to your application's Gemfile:

gem "action_policy"

And then execute:

$ bundle

Usage

Action Policy relies on resource-specific policy classes (just like Pundit).

First, add an application-specific ApplicationPolicy with some global configuration to inherit from:

class ApplicationPolicy < ActionPolicy::Base
end

Then write a policy for a resource. For example:

class PostPolicy < ApplicationPolicy
  # everyone can see any post
  def show?
    true
  end

  def update?
    # `user` is a performing subject,
    # `record` is a target object (post we want to update)
    user.admin? || (user.id == record.user_id)
  end
end

Now you can easily add authorization to your Rails* controller:

class PostsController < ApplicationController
  def update
    @post = Post.find(params[:id])
    authorize! @post

    if @post.update(post_params)
      redirect_to @post
    else
      render :edit
    end
  end
end

* See Non-Rails Usage on how to add authorize! to any Ruby project.

When authorization is successful (i.e., the corresponding rule returns true), nothing happens, but in case of authorization failure ActionPolicy::Unauthorized error is raised.

There is also an allowed_to? method which returns true or false, and could be used, in views, for example:

<% @posts.each do |post| %>
  <li><%= post.title %>
    <% if allowed_to?(:edit?, post) %>
      = link_to post, "Edit"
    <% end %>
  </li>
<% end %>

Read more in our Documentation.

Alternatives

There are many authorization libraries for Ruby/Rails applications.

What makes Action Policy different? See this section in our docs.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/palkan/action_policy.

License

The gem is available as open source under the terms of the MIT License.

You can’t perform that action at this time.