Reputation: 7172
I want to cache the results of several large queries in an fragment cache.
I could store the values in a hash and then retrieve them before making the request, but I'm wondering if the processing request could be deferred until the data is actually needed.
Here is the before code:
# 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
This is what I would LIKE the code to look like, with an anonymous object. However, I can't figure out how to pass in parameters.
# 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
Does anyone have any thoughts on how to defer the processing until the very end?
Thank you in advance!
Upvotes: 0
Views: 121
Reputation: 62668
The typical way to do this is with Procs/lambdas. You would then invoke it with #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
Upvotes: 1