【问题标题】:What's Ruby's equivalent of cached_property in python?Ruby 在 python 中的 cached_property 等价物是什么?
【发布时间】:2014-12-29 16:20:21
【问题描述】:

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

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

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

这个有 Ruby 版本吗?

【问题讨论】:

  • 您是否需要与缓存属性完全等效(即删除属性应该重置它等),或者您只是在寻找一种方便的缓存方法?在前一种情况下,它可以被编码,并且可能已经有一个宝石。在后一种情况下,使用记忆模式:justinweiss.com/blog/2014/07/28/…

标签: ruby properties attributes


【解决方案1】:

假设你的类的实例仍然存在,你只需要记住结果。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2011-03-16
    • 2019-02-12
    相关资源
    最近更新 更多