2012-02-07 37 views
0

我正在開發一個紅寶石應用程序(而不是一個軌道),我正在尋找一種非常簡單的方法來緩存一些經常使用的結果。 ,例如:緩存與實例變量在ruby with expired_after like功能

@users ||= User.all 

現在,這是工作完美,但我在尋找一種方式來添加類似到期選項,將刷新命令的每個時間段。換句話說,我需要在每個時間片段或多次後執行相同的動作。我記得在rails中我用來運行memcached並使用類似於:expire或:expired_at。

任何幫助將不勝感激。

回答

1

如何像:

class Class 
    # create a method whose return value will be cached for "cache_for" seconds 
    def cached_method(method,cache_for,&body) 
    define_method("__#{method}__".to_sym) do |*a,&b| 
     body.call(*a,&b) 
    end 
    class_eval(<<METHOD) 
     def #{method}(*a,&b) 
     unless @#{method}_cache && (@#{method}_expiry > Time.now) 
      @#{method}_cache = __#{method}__(*a,&b) 
      @#{method}_expiry = Time.now + #{cache_for} 
     end 
     @#{method}_cache 
     end 
METHOD 
    end 
end 

你可以用它喜歡:

class MyClass 
    cached_method(:users,60) do 
    User.all 
    end 
end 

這將緩存用戶60秒。如果您在經過60秒或更多秒後再次對同一對象調用users,它將再次執行方法體並更新緩存。

+0

晚餐評論。多謝亞歷克斯,這正是我在找的東西,非常感謝。乾杯 – Eqbal 2012-02-07 13:29:02

0

你不覺得上面的那個有點複雜嗎?

我嘗試類似:

Cache ={} 
def fetch(key, ttl) 
    obj, timestamp = Cache[key.to_sym] 
    if obj.nil? || Time.now - timestamp > ttl 
    obj = yield 
    Cache[key]=[obj, now] 
    end 
    obj 
end 

我很想聽聽你對這個一個