rails / jbuilder

Jbuilder: generate JSON objects with a Builder-style DSL
MIT License
4.34k stars 433 forks source link

How to preheat cache? #475

Closed asecondwill closed 4 years ago

asecondwill commented 4 years ago

How can i preheat the cache in a rake task?

cache_warmer.rake
task update_cache: :environment do
  @jobs = Job.where(archived: false).where(assignee_id: 262).each do |job|
    puts "job: #{job.id}"
    job.workspans.each do |workspan|
      json_string = ApplicationController.new.render_to_string(
        template: 'api/jobs/_workspan',
        locals: { :workspan => workspan }
      )      
      Rails.cache.write("jbuilder/views/workspan-#{workspan.id}", json)
    end
  end
end

index.jbuilder

  json.workspans(job.ordered_workspans) do |workspan|
      json.cache! "workspan-#{workspan.id}",  skip_digest: true do
         json.partial! 'workspan', workspan: workspan
      end
    end

This is almost there, but it puts escaped json in each workspan node, instead of json.

asecondwill commented 4 years ago
task update_cache: :environment do
  @jobs = Job.where(archived: false).where(assignee_id: 262).each do |job|
    puts "job: #{job.id}"
    job.workspans.each do |workspan|
      json_string = ApplicationController.new.render_to_string(
        template: 'api/jobs/_workspan',
        locals: { :workspan => workspan }
      )
      Rails.cache.write("jbuilder/views/workspan-#{workspan.id}", JSON.parse(json_string))
    end
  end
end

Have to parse it to json istead of saving a string. sorry, not sure I could belive it was that simple after a long time getting the other parts working.