如何在Rails3中的业务逻辑中访问Warden当前用户
我正在使用 Rails Warden 插件。它定义了一个辅助方法返回当前的'user'用户。请参阅源代码链接。
现在我有一个业务逻辑对象,它没有任何对控制器的引用。但我想获得当前用户。有什么方法可以访问这个吗?
我已经尝试过
ActionController::Base.helpers.user
,甚至
RailsWarden::Mixins::HelperMethods.user
没有运气。谢谢。
I am using Rails Warden plugin. It defines a helper method 'user' that returns current user. See the link for the source code.
Now I have an business logic object that does not have any reference to the controller. But I would like to get the current user. Is there any way of accessing this?
I have tried
ActionController::Base.helpers.user
or even
RailsWarden::Mixins::HelperMethods.user
with no luck. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那么为什么不能将当前用户传递给这些方法呢?
另外,您可以将它们混合在一起。
我强烈建议您编写静态助手(它不是 Java,而是 Ruby!)。
相反,在您需要这些帮助器的地方将它们作为模块包含:
然后在您需要的地方包含它:
依此类推...
此外,在访问业务逻辑的地方,您可以只创建类的实例而不是“静态”方法(在 ruby 中,它们是“类”方法):
这可能是您可以做的最简单的事情。
实际上,您不需要访问业务对象中的整个 HTTP 上下文(我什至没有谈论测试它)。
So why can't you just pass the current user to those methods?
Additionally you can mix them in.
I strongly discourage you to write the static helpers (it is not Java, it is Ruby!).
Instead, where you need those helpers include them as a module:
Then include this where you need it:
and so on...
additionally where you access your business logic, you can just create an instance of the class instead of "static" methods (in ruby they are "class" methods):
This is probably the easiest thing you can do.
Really, you don't need to access whole HTTP context in your business objects (I'm not even talking about testing it).
我对业务逻辑的看法是,它位于控制器和模型之间。我认为将请求的实例传递给逻辑方法是可以的,并且由于您使用的是 Warden,因此您可以从“request.env['warden'].user”获取用户。
我还没有遇到不让逻辑方法成为模块的静态(自身)方法的充分理由。也许 Dmytrii 的建议适合您,但我更喜欢“要求”而不是动态地包含一次性逻辑位。
The way I think of business logic, it's something that sits between the controller and the model. I think it would be ok to pass an instance of the request to the logic methods, and since you're using warden, you can get the user from 'request.env['warden'].user'.
I haven't encountered a good reason not to have logic methods be static (self.) methods of a module. Maybe Dmytrii's suggestion works for you, but I prefer to 'require' than to dynamically include one-off logic bits.