什么是Ruby相当于python中的cached_property?

时间:2014-11-03 02:34:44

标签: ruby properties attributes

基本上,我有一个Ruby类,它有一个属性可以进行昂贵的HTTP调用来获取一些值,我需要缓存该值,所以下次访问该属性时我不必再次调用HTTP。 / p>

http://pydanny.com/cached-property.html

https://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties

这是否有Ruby版本?

1 个答案:

答案 0 :(得分:0)

假设类的实例仍然存在,则只需记住结果即可。

class Foo
  def http_response
    @_http_response ||= begin
      # your slow I/O bound code here
    end
  end
end

除非该块的结果为假,否则将不会再次执行。此概念有多种变体,例如:

class Foo
  def http_response(skip_cache = false)
    return @_http_response unless skip_cache || !@_http_response
    @_http_response = fetch_http_response
  end

  private
    def fetch_http_response
      # your slow I/O bound code here
    end
end