Search code examples
ruby-on-rails-3sidekiqpdfkit

render_to_string in sidekiq worker


I'm trying to do some PDF generation in my app which processes some data and then creates the PDF of the result. I'm using PDFKit so need to simply create an HTML view which is fine if I'm in a controller, but I want to push the processing into a background thread with Sidekiq.

I had planned to use render_to_string but due to it being part of a Controller only, I can't use it in Sidekiq.

Is there some way I can do this? I'd like to try and stick with Sidekiq but if not then I guess I just have to do it all within the controller?


Solution

  • OK I've gone for a different approach.

    I've created an abstract controller that is being called directly from the worker class, as describe here http://www.whatastruggle.com/generating-pdfs-in-background

    Thanks anyway

    Edit

    Seems the link is dead, so to sum up what worked:

    Create a new controller, this will be the rendering controller

    rendering_controller.rb

    class RenderingController < AbstractController::Base
      include AbstractController::Rendering
      include ActionView::Layouts
      include AbstractController::Helpers
      include AbstractController::Translation
      include AbstractController::AssetPaths
      include Rails.application.routes.url_helpers
      include WickedPdf::PdfHelper
    
      self.view_paths = 'app/views'
    end
    

    Then wherever you need to use it

    rc = RenderingController.new
    rc.render_to_string(template: 'template/name', locals: { local: value })
    

    Note this is no longer required if you're using Rails 5+ since they enabled rendering outside of controllers. Instead you can now just do:

    ApplicationController.render :index
    

    More details are available here