实施基于角色的助手

发布于 2024-08-27 15:12:47 字数 729 浏览 9 评论 0原文

所以我的问题是,您将如何根据当前用户的角色实现手写的助手。

在请求时更改行为是否高效?例如,帮助程序以某种方式找出用户的角色,并包含适当的子模块?

module ApplicationHelper
    module LoggedInHelper
        # Some functions
    end

    module GuestHelper
        # The Same functions
    end

    # If User is Guest then include GuestHelper
    # If User is LoggedIn then include LoggedInHelper

end

这样有效率吗?是铁路方式吗?我有一大堆像这样的函数,我不想将它们中的每一个都包装在 if 语句中,

def menu_actions
    if current_user.nil?
        # User is guest
        { "Log in" => link_to "Login", "/login" }
    else
        # User is Logged In
        { "Log out" => link_to "Logout", "/logout" }
    end
end

谢谢您的时间和想法。

So my question is how would you implement your handwritten Helpers based on the role of current user.

Would it be efficient to change the behaviour at request time? e.g. the Helper somehow figures out the role of user, and include the proper SubModule?

module ApplicationHelper
    module LoggedInHelper
        # Some functions
    end

    module GuestHelper
        # The Same functions
    end

    # If User is Guest then include GuestHelper
    # If User is LoggedIn then include LoggedInHelper

end

Is it efficient this way? is it rails way? I've got a whole bunch of function that act like this, and I don't want to wrap every single one of them in an if statement

def menu_actions
    if current_user.nil?
        # User is guest
        { "Log in" => link_to "Login", "/login" }
    else
        # User is Logged In
        { "Log out" => link_to "Logout", "/logout" }
    end
end

Thank you for your time and thoughts.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白色秋天 2024-09-03 15:12:47

我不相信这会起到很好的作用。在开发模式下,它可能会起作用,但在生产中,代码不会随着每个请求从头开始加载。这意味着第一个请求将加载正确的模块,但之后下一个请求可能会加载第二个模块,然后就会出现冲突。

关于如何避免 switch 语句或 if 语句,我没有一个好的答案,但怀疑类继承系统将是替代模块包含的最佳选择。

I don't believe this would work very well at all. In dev mode, it would probably behave, but in production the code doesn't get loaded from scratch with each request. That means the first request would load the proper module, but after that the next request might load a second module and then there would be conflict.

I don't have a good answer for you about how to avoid switch statements or if statements, but suspect that a class inheritance system would be the way to go instead of module inclusion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文