实施基于角色的助手
所以我的问题是,您将如何根据当前用户的角色实现手写的助手。
在请求时更改行为是否高效?例如,帮助程序以某种方式找出用户的角色,并包含适当的子模块?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不相信这会起到很好的作用。在开发模式下,它可能会起作用,但在生产中,代码不会随着每个请求从头开始加载。这意味着第一个请求将加载正确的模块,但之后下一个请求可能会加载第二个模块,然后就会出现冲突。
关于如何避免 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.