# Action Policy

> An authorization framework for Ruby on Rails applications.

- URL: https://evilmartians.com/opensource/action-policy
- GitHub: https://github.com/palkan/action_policy
- Website: https://actionpolicy.evilmartians.io/
- Authors: Vladimir Dementyev

---

Action Policy is a composable, extensible, and performant authorization framework for Ruby on Rails applications.

## Usage

Action Policy relies on resource-specific policy classes (just like [Pundit](https://github.com/varvet/pundit)).

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

```ruby
class ApplicationPolicy < ActionPolicy::Base
end
```

This may be done with the `rails generate action_policy:install` generator.

Then, write a policy for a resource. For example:

```ruby
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
```

This may be done with the `rails generate action_policy:policy Post` generator.

Now you can easily add authorization to your Rails controller:

```ruby
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
```

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

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

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

Read more in the [Documentation](https://actionpolicy.evilmartians.io/).
