每个用户只有一个角色的cancan-以任何方式设置能力而无需重复太多文本? [英] cancan with one role per user - any way to set up abilities without repeating so much text?

查看:72
本文介绍了每个用户只有一个角色的cancan-以任何方式设置能力而无需重复太多文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的能力模型如下所示:

My ability model looks something like this:

class Ability
    include CanCan::Ability

    def initialize(user)
        if user.role == "moderator"
            can :manage, [Forum, Post]
        elsif user.role == "admin"
            can :manage, [Enrollment, SiteCare, Forum, Post]
        elsif user.role == "superadmin"
            can :manage, [Permission, Enrollment, SiteCare, Forum, Post]
        end
    end
end

实际上,某些角色有十几个他们管理的项目。为了简化事情,我该如何构造一些红宝石,使我不必重复太多文本?

In reality some of the roles have a dozen items they manage. To simplify things how can i construct some ruby that would keep me from having to duplicate so much text? Perhaps something like this construct?

class Ability
    include CanCan::Ability

    def initialize(user)
        a = "Forum, Post"
        b = "Enrollment, SiteCare"
        c = "Permission"

        if user.role == "moderator"
            can :manage, [{a}]
        elsif user.role == "admin"
            can :manage, [{a + b}]
        elsif user.role == "superadmin"
            can :manage, [{a + b + c}]
        end
    end
end

谢谢。

PS我知道每个用户方法都有多个角色(位掩码单独的角色模型),并且不希望设置其他模型或数据库表。

P.S. I am aware of the multiple role per user methods (bitmask and Separate Role Model) and prefer not setting up the additional models or database tables.

推荐答案

我自己使用了单独的角色模型。
按照您的代码模型,我可以考虑一种方法。合并字符串,然后对于每个对象(用冒号分隔),使用 constantize ,因此您将获得一个常数。

I use the Separate Role Model myself. Following your code model, I can think of a way. Merge the strings, then for each object (separated by colons) use constantize, so you will get a constant.

class Ability
    include CanCan::Ability

    def initialize(user)
        a = "Forum,Post"
        b = "Enrollment,SiteCare"
        c = "Permission"

        if user.role == "moderator"
            can :manage, permissions(a)
        elsif user.role == "admin"
            can :manage, permissions(a, b)
        elsif user.role == "superadmin"
            can :manage, permissions(a, b, c)
        end
    end

  private
    # TODO: think of a better function name?
    def permissions(*args)
        args.join(",").split(",").map(&:constantize)
    end
end

必须先进行联接,然后进行拆分。您加入所有字符串,然后将每个类(论坛,帖子等)分成一个新字符串。完成之后,您可以对每个字符串调用常量化,从而获得一个可以使用的常量。 论坛->论坛

The join followed by a split is necessary. You join all the strings, and then separate each class (forum, post etc.) into a new string. After that is done, you call constantize on each string, receiving a constant which you can use. "Forum" -> Forum

我使用irb进行了基本测试,但没有进行常量化,它似乎运行良好。试试吧!

I did basic tests with irb without the constantize and it seems to be working fine. Try it!

这篇关于每个用户只有一个角色的cancan-以任何方式设置能力而无需重复太多文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆