2012-02-03 21 views
53

所以在Rails 3.2中,ActiveSupport :: Memoizable已被棄用。哪個Ruby memoize模式ActiveSupport :: Memoizable是指?

賀電:

DEPRECATION WARNING: ActiveSupport::Memoizable is deprecated and 
will be removed in future releases,simply use Ruby memoization 
pattern instead. 

它指的是「紅寶石記憶化模式」(單數),就好像有一個模式大家應該都知道,並指...

我相信他們意味着什麼像:

def my_method 
    @my_method ||= # ... go get the value 
end 

def my_method 
    return @my_method if defined?(@my_method) 

    @my_method = # ... go get the value 
end 

還有別的我錯過了嗎?

+0

如果你想「假」或「零」,它不會被使用Ruby的memoizable保存。所以如果你想實現你自己的memoizable包裝,添加一種方法來保存'假'和'零'。 – rubies 2013-05-05 19:36:38

回答

36

這裏是提交(和隨後的討論),其中Memoizable被棄用:https://github.com/rails/rails/commit/36253916b0b788d6ded56669d37c96ed05c92c5c

作者主張@foo ||= ...方法和points to this commit作爲遷移的示例:https://github.com/rails/rails/commit/f2c0fb32c0dce7f8da0ce446e2d2f0cba5fd44b3

編輯: 請注意,我不一定將此更改解釋爲意思是memoize的所有實例都可以或應該替換爲此模式。我把它理解爲意味着Rails代碼本身不再需要/需要Memoizable。正如評論指出的那樣,Memoizable不僅僅是一個圍繞@foo ||= ...的包裝。如果您需要這些功能,請繼續使用Memoizable,您只需要從ActiveSupport以外的其他地方獲取它(我猜如果他們還沒有的話,有人會分叉一個寶石版本)。

31

另一種選擇是使用Memoist寶石:

距離ActiveSupport::Memoizable直接提取和可以用作一個簡易替換。只是require 'memoist'和更改

extend ActiveSupport::Memoizable 

extend Memoist 
0

基於該評論上the commitreferenced above by avaynshtok,我有這個打算:

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

...因爲我想我會知道什麼時候我的RSpec套件中的ActiveSupport從最初的門開始冒出了Memoizable

3

只是一個除了頂部的答案,以memoize的類方法使用以下模式:

class Foo 
    class << self 
    def bar 
     @bar ||= begin 
     # ... 
     end 
    end 
    end 
end 
相關問題