Last active
August 29, 2015 14:05
-
-
Save dmitry/83ef4684aee3bda002f8 to your computer and use it in GitHub Desktop.
application_policy.rb with permitted_params or permitted_attributes used in active_admin
This file contains 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 | |
attr_reader :user, :record | |
def initialize(user, record) | |
@user = user | |
@record = record | |
end | |
def index? | |
true | |
end | |
def show? | |
scope.where(:id => record.id).exists? | |
end | |
def create? | |
true | |
end | |
def new? | |
create? | |
end | |
def update? | |
true | |
end | |
def edit? | |
update? | |
end | |
def destroy? | |
false | |
end | |
def scope | |
Pundit.policy_scope!(user, record.class) | |
end | |
def permitted_params | |
@permitted_params = PermittedParams.new(self, &@@permit_params) | |
end | |
def self.permit_params(&block) | |
@@permit_params = block | |
end | |
protected | |
class PermittedParams < Array | |
attr_reader :user, :record | |
def initialize(policy, &block) | |
@policy = policy | |
@block = block | |
@user = policy.user | |
@record = policy.record | |
process | |
end | |
def new? | |
record.is_a?(Class) || record.new_record? | |
end | |
def [](v) | |
@hash ||= self.class.to_hash(self) | |
!!@hash[v] | |
end | |
private | |
def process | |
instance_eval(&@block) | |
end | |
def self.to_hash(array) | |
Hash[*array.flat_map do |v| | |
if v.is_a?(Hash) | |
hk, kv = v.first | |
[hk, (kv.is_a?(Array) ? to_hash(kv) : true)] | |
else | |
[v, true] | |
end | |
end] | |
end | |
end | |
end |
This file contains 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 PropertyPolicy < ApplicationPolicy | |
permit_params do | |
concat([{translations_attributes: [:id, :name, :description, :locale]}]) | |
if (user.admin? || user.super_admin?) || new? | |
concat([ | |
:price, | |
{type_ids: []} | |
]) | |
end | |
end | |
end | |
ActiveAdmin.register Property do | |
decorate_with PropertyDecorator | |
permit_params do | |
policy(resource).permitted_params | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment