Created
July 19, 2019 21:00
-
-
Save danielpowell4/4a8aa47100d5a2940ea9b43cce19994c to your computer and use it in GitHub Desktop.
CanCanCan ability delegator. Like alias_action but across model classes
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
# frozen_string_literal: true | |
module Abilities | |
module AbilityDelegator | |
def self.included(klass) | |
klass.class_eval do | |
def delegate_action(action_or_actions, to:, traversal:, user:) | |
actions = [*action_or_actions] | |
can actions, model_class do |instance| | |
delegate = traversal.reduce(instance, &:public_send) | |
user_ability = "::Abilities::#{delegate.class.name}Ability".constantize.new(user) | |
user_ability.can?(to, delegate) | |
end | |
end | |
private | |
def model_class | |
self.class.name.sub('Abilities::', '').sub('Ability', '').constantize | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment