通过模块共享范围?
我想通过将共享范围移动到模块中来干燥多个模型,例如:
module CommonScopes
extend ActiveSupport::Concern
module ClassMethods
scope :ordered_for_display, order("#{self.to_s.tableize}.rank asc")
end
end
我还想创建测试模块的共享规范。不幸的是,当我尝试将共享范围包含在我的模型中时,我得到:
undefined method `order' for CommonScopes::ClassMethods:Module
有什么想法吗?谢谢!
I want to DRY up several models by moving shared scopes into a module, something like:
module CommonScopes
extend ActiveSupport::Concern
module ClassMethods
scope :ordered_for_display, order("#{self.to_s.tableize}.rank asc")
end
end
I also want to create shared specs that test the module. Unfortunately when I try to include the shared scope in my model I get:
undefined method `order' for CommonScopes::ClassMethods:Module
Any ideas? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与 Rails 4 中一样,您可以简单地使用 lambda 来延迟代码的执行(适用于 Rails 3)也):
As in rails 4 scope syntax you can simply use a lambda to delay the execution of the code (works in rails 3 too):
您可以使用 instance_eval
You can use instance_eval
因为当您的模块被 Ruby 解析时,您的
scope
方法会立即被调用,并且无法从您的CommonScopes
模块访问它。但是您可以用类方法替换您的作用域调用:
Because your
scope
method is called immediately when your module is parsed by Ruby and it's not accessible from yourCommonScopes
module..But you can replace your scope call by a class method: