Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Created July 19, 2019 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpowell4/4a8aa47100d5a2940ea9b43cce19994c to your computer and use it in GitHub Desktop.
Save danielpowell4/4a8aa47100d5a2940ea9b43cce19994c to your computer and use it in GitHub Desktop.
CanCanCan ability delegator. Like alias_action but across model classes
# 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