Search code examples
ruby-on-railsabstractcache-digests

Rails cache_digests and AbstractControllers


I have a class that I use to render some pdfs inheriting from AbstractController and I'd like to use cache_digests in the views

class PDFExporter < AbstractController::Base
  include AbstractController::Rendering
  include ActionView::Layouts
  include AbstractController::Helpers
  include AbstractController::Translation
  include AbstractController::AssetPaths
  include AbstractController::Callbacks

  helper ApplicationHelper, FormatterHelper, FontAwesome::Rails::IconHelper
  view_paths << "app/views"

  TMP_PATH = File.join(Rails.root, "tmp")
  PDFTK_PATH = "/usr/bin/pdftk"
  LAYOUT = "pdf.html.erb"
  COVER = "shared/pdf_cover.html.haml"
  MARGINS = {top: 17, left: 0, right: 0, bottom: 9.5}

  def self.save_pdf_file(pdf)
    file = Tempfile.new("pdf", encoding: "ASCII-8BIT")
    file.write(pdf)
    file
  end

  protected
  def generate_pdf(templates)
    partials = generate_partials(templates)
    output = File.join(TMP_PATH, "#{filename}.pdf")
    paths = partials.map(&:path).join(" ")
    system("#{PDFTK_PATH} #{paths} cat output #{output}")
    partials.map(&:unlink)
    output
  end

  private
  def generate_partials(templates)
    templates.map do |template|
      partial = send("partial_#{template.shift}", *template)
      PDFExporter.save_pdf_file(partial)
    end
  end

  def partial_content(template)
    rendered = render(template: template, layout: LAYOUT)
    WickedPdf.new.pdf_from_string(rendered,
      orientation: "Landscape",
      margin: MARGINS,
      header: {
        spacing: 3,
        content: render_to_string("shared/pdf_header.pdf.haml",
        layout: LAYOUT)
      },
      footer: {
        content: render_to_string("shared/pdf_footer.pdf.haml",
        layout: LAYOUT)
      }
    )
  end

  def partial_cover(template = COVER)
    rendered = render(template: template, layout: LAYOUT)
    WickedPdf.new.pdf_from_string(rendered, orientation: "Landscape",
      margin: MARGINS, header: nil, footer: nil)
  end
end

when I try to call cache in the view

- cache [@fund, @fund_sheet.report_date] do

I get:

undefined method `perform_caching' for #<FundSheet::Exporter:0x0000000e128e10>

I've tried to include some caching modules in it but I can make it work


Solution

  • I got it!

    class PDFExporter < ActionController::Metal
      <...>
      include ActionController::Caching
      config.cache_store = Rails.cache
      <...>
    end