使用 Rails Presenters - memoizable 在 3.1 中被弃用 - 使用 ||= 代替?
问题:尽可能避免创建多个对象或多个查询。
我使用带有 Rails 的 Presenter 作为最佳实践。
我遵循的建议是,最好使用“extend ActiveSupport.Memoizes”(然后记忆:使用它们的方法)而不是使用 @the_record = record ||= @record< 设置项目/code> 样式,因为有几个问题 - false 或 nil 没有被存储,因此查询被再次调用,并且 memoible 更好地使用缓存(即使用它!)。
然而我发现 memoible 在 Rails 3.1 中已被弃用 笔记我github下的Carrierwave和声明: “弃用警告:ActiveSupport::Memoizes 已弃用,并将在未来版本中删除,只需使用 Ruby 记忆模式即可。(从 /Users/kain/.rvm/gems/ruby-1.9.3-preview1/bundler/ 的扩展中调用) gems/rierwave-c4459179b0f8/lib/carrierwave/mount.rb:284”。
也许已经解决了吗?有人知道
如何使用 ||= 语法吗
? " alt="在此处输入图像描述">
Issue: To avoid creating multiple objects or multiple queries when possible.
I am using Presenters with rails as a Best Practice.
I am following advice that says that it would be good to use "extend ActiveSupport.Memoizable" (and then memoize :method(s) to use them) over setting up items with @the_record = record ||= @record
style because of a couple of issues - false or nil not getting stored so the query gets called again and also that memoizable uses the cache better (i.e. uses it!).
However I see that memoizable is getting deprecated in rails 3.1
Notes i github under carrierwave and with statement:
"DEPRECATION WARNING: ActiveSupport::Memoizable is deprecated and will be removed in future releases,simply use Ruby memoization pattern instead. (called from extend at /Users/kain/.rvm/gems/ruby-1.9.3-preview1/bundler/gems/carrierwave-c4459179b0f8/lib/carrierwave/mount.rb:284".
Maybe it's been resolved though? Anyone know?
Any suggestions about the best practice to use going forward? Use the ||= syntax? What about the above issues?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
||=
方法对于返回计算结果为 true 的值的情况非常有用,但对于返回值不为 true 的情况则效果不佳。memoize
通过捕获这些条件并相应地返回来解决这个问题。如果您想容纳 nil,您可以采取这样的方法:这只是检查变量是否已定义,而不是是否已设置,这在您的情况下是一个重要的区别。
我不确定为什么您认为它已被弃用 [Michael 的注释,它在 3.2 中已弃用,请参阅下面的注释]。 文档表明它仍然是 3.1 版本。有时,当实现从一个模块移动到另一个模块时,它们会被标记为“已弃用”,但该功能仍然可用。
The
||=
method is great for things that return values that evaluate as true, but it doesn't work very well for things that don't.memoize
does work around this by trapping these conditions and returning accordingly. You might take an approach like this if you want to accommodatenil
:This just checks if the variable is defined, not if it is set, which is an important distinction in your case.
I'm not sure why you think it's being deprecated [Note from Michael, it's deprecated in 3.2, see note below]. The documentation indicates it's still current in 3.1. Sometimes implementations are marked as "deprecated" when they're being moved from one module to another, but the facility remains available.