Skip to content
Joe Acklin edited this page Apr 19, 2016 · 2 revisions

Background

Canner provides the method has_role? method to allow you to easily check if a user has a particular role.

  def can?
    case @method
    when :destroy
      has_role?(:sysop)
    else
      false
    end
  end

In order for this method to work it needs to know what roles the current_user has.

By default canner will assume your user roles are available by the following:

@current_user.roles

If that's the case then you won't need to change anything. The rest of this doc is to show you how to feed canner the user role information from your app.

Feeding Roles

The best way to start is to use the generator provided.

rails g canner:fetch_roles

This will create a base_policy.rb for you inside your app/polices directory.

Its pretty basic and looks like this:

class BasePolicy < Canner::Policy
  # results expected to be an array or strings or symbols that represent the user roles
  def fetch_roles
    @current_user.roles
  end
end

Just replace adjust the implementation of the fetch_roles method to suit your app. Note the comment that the return value is expected to be an array of roles. Strings or symbols both are fine.

Don't forget that your model polices will need to inherit from BasePolicy now, not Canner::Policy You can still use the generator to build new policies for you but you'll want to pass the parent option:

rails g canner:policy Order --parent BasePolicy

Since my project is using the branch authorization feature it needs to override the fetch_roles method as described above. We have a Permissions object that contains the users role at a specific branch so our fetch_roles implementation is something like:

def fetch_roles
  Permission.roles(@current_user, @current_branch)
end
Clone this wiki locally