Which Ruby memoize pattern does ActiveSupport::Memoizable refer to?

岁酱吖の 提交于 2019-12-02 17:15:17

Here is the commit (and subsequent discussion) where Memoizable was deprecated: https://github.com/rails/rails/commit/36253916b0b788d6ded56669d37c96ed05c92c5c

The author advocates the @foo ||= ... approach and points to this commit as an example for migration: https://github.com/rails/rails/commit/f2c0fb32c0dce7f8da0ce446e2d2f0cba5fd44b3.

Edit: Note that I don't necessarily interpret this change as meaning that all instances of memoize can or should be replaced w/ this pattern. I read it as meaning that Memoizable is no longer needed/wanted in the Rails code itself. As the comments point out, Memoizable is much more than just a wrapper around @foo ||= .... If you need those features, go ahead and use Memoizable, you'll just have to get it from somewhere other than ActiveSupport (I'm guessing someone will fork a gem version, if they haven't already).

jcfischer

Another option is to use the Memoist gem:

It is a direct extraction from ActiveSupport::Memoizable and can be used as a drop-in replacement. Just require 'memoist' and change

extend ActiveSupport::Memoizable

to

extend Memoist

Just an addition to the top answer, to memoize a class method use the following pattern:

class Foo
  class << self
    def bar
      @bar ||= begin
        # ...
      end
    end
  end
end
aec

Based upon the comments on the commit referenced above by avaynshtok, I’m going with this:

ActiveSupport::Deprecation.silence { extend ActiveSupport::Memoizable }

… because I figure I’ll know when Memoizable is ripped out of ActiveSupport from my RSpec suite dying right out of the starting gate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!