如何像:
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
,它將再次執行方法體並更新緩存。
晚餐評論。多謝亞歷克斯,這正是我在找的東西,非常感謝。乾杯 – Eqbal 2012-02-07 13:29:02