rails 使用匿名缓存 类

rails caching with anonymous classes

我想在片段缓存中缓存几个大型查询的结果。

我可以将值存储在哈希中,然后在发出请求之前检索它们,但我想知道是否可以将处理请求推迟到实际需要数据时。

这是之前的代码:

# controller

class MyController < ApplicationController
  def my_action
    @my_huge_query_with_1_result = do_massive_question
  end
end

# my_action.html.slim

.header
  = cache do
    ' Your answer is
    = @my_huge_query_with_1_result

这就是我希望代码看起来像的样子,带有一个匿名对象。但是,我不知道如何传入参数。

# controller

class MyController < ApplicationController
  def my_action
    @my_cache = Object.new
    def @my_cache.do_query
      do_massive_question(params) # this fails; because params is not in the scope of @my_cache's class.
    end
  end
end

# my_action.html.slim

.header
  = cache do
    ' Your answer is
    = @my_cache.do_query

有没有人对如何将处理推迟到最后有任何想法?

提前致谢!

执行此操作的典型方法是使用 Procs/lambdas。然后您可以使用 #call.

调用它
def my_action
  @my_huge_query_with_1_result = ->{ do_massive_question(params) }
end

# View
.header
  = cache do
    ' Your answer is
    = @my_huge_query_with_1_result.call