Skip to content

Instantly share code, notes, and snippets.

@abriening
Last active December 15, 2015 21:19
Show Gist options
  • Save abriening/5324745 to your computer and use it in GitHub Desktop.
Save abriening/5324745 to your computer and use it in GitHub Desktop.
class PostPolicy < Struct.new(:user, :post)
def update?
post.user == user
end
def destroy?
false
end
def show?
true
end
end
class Ability
include CanCan::Ability
def initialize(user)
@user = user || User.new
can do |action, object|
policy(object).send_public(policy_method(action))
end
end
def policy_method(action)
"#{action}?"
end
def policy(object)
find_policy(object).new(@user, object)
end
def find_policy(object)
if object.respond_to?(:policy_class)
object.policy_class
elsif object.class.respond_to?(:policy_class)
object.class.policy_class
else
model = if object.respond_to?(:model_name)
object.model_name
elsif object.class.respond_to?(:model_name)
object.class.model_name
elsif object.is_a?(Class)
object
else
object.class
end
Object.const_get("#{model}Policy")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment