Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 用于缓存结果的Ruby on Rails装饰器?_Ruby On Rails_Ruby_Caching_Decorator_Memoization - Fatal编程技术网

Ruby on rails 用于缓存结果的Ruby on Rails装饰器?

Ruby on rails 用于缓存结果的Ruby on Rails装饰器?,ruby-on-rails,ruby,caching,decorator,memoization,Ruby On Rails,Ruby,Caching,Decorator,Memoization,在Python中,您可以编写一个decorator来记录函数的响应 RubyonRails有类似的功能吗?我有一个模型的方法来进行查询,我想缓存它 我知道我可以在方法内部做一些事情,比如: def foo(param) if self.cache[param].nil? self.cache[param] = self.get_query_result(param) else self.cache[param] end end 然而,考虑到我经常这样做,我更喜欢de

在Python中,您可以编写一个decorator来记录函数的响应

RubyonRails有类似的功能吗?我有一个模型的方法来进行查询,我想缓存它

我知道我可以在方法内部做一些事情,比如:

def foo(param)
  if self.cache[param].nil?
    self.cache[param] = self.get_query_result(param)
  else
    self.cache[param]
  end
end
然而,考虑到我经常这样做,我更喜欢decorator语法。在国际海事组织,它更清晰、更好


RubyonRails有类似的功能吗?

我通常使用自定义访问器、实例变量和
|124;=
操作符来实现这一点:

def foo
  @foo ||= something_or_other
end
something\u或\u other
可以是同一类上的私有方法,该类返回
foo
应该是的对象

编辑

这里有一个稍微复杂一点的解决方案,它允许您根据用于调用方法的参数缓存任何方法

class MyClass
  attr_reader :cache
  def initialize
    @cache = {}
  end

  class << self
    def cacheable(symbol)
      alias_method :"_#{symbol}_uncached", symbol

      define_method(symbol) do |*args|
        cache[[symbol, *args]] ||= (send :"_#{symbol}_uncached", *args)
      end
    end
  end
end
首先,方法是正常定义的。然后调用类方法
cacheable
,该类方法将原始方法别名为新名称,然后在原始名称下重新定义它,仅当它尚未缓存时才执行。它首先使用相同的方法和参数检查缓存中的任何内容,如果存在,则返回值,如果不存在,则执行原始方法。

:

在计算机科学中只有两件困难的事情:缓存失效和命名

--菲尔·卡尔顿

Rails有很多内置缓存(包括查询缓存)。您可能不需要执行任何操作:

以下是最近一篇关于roll your own caching问题的博客文章:


嗯,我想这不是解决你问题的好办法。敬请期待。
class MyClass
  def foo(a, b)
    a + b
  end

  cacheable :foo
end