Last active
August 29, 2015 14:04
-
-
Save panSarin/03a4ad9fffba559aae56 to your computer and use it in GitHub Desktop.
Pundit policies and our controllers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationPolicy | |
# ... content generated by pundit (its about access for actions - we will discuss it in part 2 of that blogpost) | |
class Scope # our default scope for each model | |
attr_reader :user, :scope | |
def initialize(user, scope) | |
@user = user | |
@scope = scope | |
end | |
def resolve | |
if user.is_superadmin? | |
scope.all | |
else | |
scope.where(company_id: user.company_id) | |
end | |
end | |
end | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ClientPolicy < ApplicationPolicy | |
class Scope < Scope | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ClientSearch | |
# some simple class for searching clients that also use policy_scoped | |
# as u can see its also easy useable in other classes than controller | |
attr_reader :user | |
def initialize(args={}) | |
args.each do |k,v| | |
instance_variable_set("@#{k}", v) unless v.nil? | |
end | |
end | |
def search | |
res = policy_scoped(Client) | |
res = res.where(city: @city) if @city.present? | |
#... rest of search method logic | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ClientsController < AgencyScopedController | |
before_filter :set_client, only: [:show, :edit, :update, :destroy] | |
def index | |
@clients = policy_scope(Client).paginate(per_page: 20, page: params[:page]) | |
end | |
def search | |
@clients = ClientSearch.new(params[:search].merge({user: current_user})).search | |
end | |
private | |
def set_client | |
@client = policy_scope(Client).find(params[:id]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment