Last active
December 19, 2021 01:48
-
-
Save mewdriller/4980855 to your computer and use it in GitHub Desktop.
Serializing CanCan rules to JSON for use in a client-side application
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 Ability | |
| include CanCan::Ability | |
| def initialize(user) | |
| can :read, Comment | |
| if user.valid? | |
| can :create, Comment | |
| can :manage, Comment, author_id: user.id | |
| end | |
| end | |
| def as_json | |
| abilities = [] | |
| rules.each do |rule| | |
| abilities << { can: rule.base_behavior, actions: rule.actions.as_json, subjects: rule.subjects.map(&:to_s), conditions: rule.conditions.as_json } | |
| end | |
| abilities | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, just dropping a note - love this solution, but found something useful - if you use
rule.instance_variable_get('@expanded_actions')it allows you to serialize all actions that are aliased. For example:Will serialize all aliased actions for
crudNote:
The one "gotcha" of this approach is that you have to call
can?(:initialize, :abilities)in theas_jsonmethod to initialize theexpanded_actionsvariable for each rule. This is somewhat weird behavior, but you can't get around it because the CanCan module really kicks off with a call tocan?() or cannot?(). Otherwise,expanded_variableswill not be set.