如何在 ruby 中缓存方法?

How to cache methods in ruby?

我有一个 ruby 工作流程,它几乎不需要进行昂贵的 API 调用。我知道我们有一种更简单的方法可以在 Rails 上的 Ruby 中缓存内容,但还没有找到 ruby 脚本的任何常见 ruby gem。

对于依赖于纯 ruby 应用程序输入的方法,缓存结果的最简单方法是什么?

//pseudo code
def get_information (id)
  user_details = expensive_api_call(id)
  return user_details
end

最简单的方法是使用哈希:

class ApiWithCache

  def initialize
    @cache = {}
  end

  def do_thing(id)
    expensive_api_call(id)
  end

  def do_thing_with_cache(id)
    @cache[id] ||= do_thing(id)
  end
end

现在这提出了一些您可能想要研究的问题:

  • 缓存数据过期
  • 缓存大小(除非您也删除项目,否则会增加。这可能会导致长 运行 进程出现问题)

您可以使用包含散列的实例变量和 ||= 运算符来执行此操作,如:

def initialize
  @user_cache = {}
  # ...
end

def get_information(id)
  @user_cache[id] ||= expensive_api_call(id)
end

||= 表示仅当左值(在本例中为 @user_cache[id])为假(nil 或 false)时才执行方法调用并执行赋值。否则,使用散列中已有的值。

纯ruby:

已经很简单了
def foo(id)
  @foo[id] ||= some_expensive_operation
end

就宝石而言 - 查看 memoist

通过hash全局变量来做

def get_information(id)
    @user_details ||= {}
    @user_details[id] ||= expensive_api_call(id)
    return @user_details[id]
end

尝试 zache:

require 'zache'
zache = Zache.new
x = zache.get(:x, lifetime: 15) do
  # Something very slow and expensive, which
  # we only want to execute once every 15 seconds.
end

我是作者