Extending view to generate PDF returns error after upgrade to Rails 6.1

Viewed 209

Until recently I extended the Rails view to generate a PDF in a service object:

view = ActionView::Base.new(ActionController::Base.view_paths, {})
view.extend(ApplicationHelper)
view.extend(Rails.application.routes.url_helpers)

WickedPdf.new.pdf_from_string(
  view.render(
    pdf: pdf_title,
    template: template,
    locals: { timesheet: timesheet },
    print_media_type:  true,
    orientation:       'Portrait',
    page_size:         'A4'
  )
)

After upgrading to Rails 6.1, this gives an error, because there has been a change in this line:

view = ActionView::Base.new(ActionController::Base.view_paths, {})

There is now a 3rd parameter controller mandatory according to this commit in the Rails source. This:

def initialize(lookup_context, assigns = {}, controller = nil)

Changed to this:

def initialize(lookup_context, assigns, controller)

But I am not sure what controller is in this case and what I should provide as 3rd parameter, as this is all called from a service object an not a controller. Also just adding a nil value as 3rd parameter is not working, because then the PDF is unreadable when opened, so I guess it doesn't extend the view properly.

So any idea what value to provide as 3rd parameter?

1 Answers

If you use one of your base controller to render, instead of the view, you may be able to get the html you need. Using a controller that already has the route and view helpers in it will also alleviate the need to manually extends/include them.

WickedPdf.new.pdf_from_string(
  ApplicationController.renderer.render(
    pdf: pdf_title,
    template: template,
    locals: { timesheet: timesheet },
    print_media_type:  true,
    orientation:       'Portrait',
    page_size:         'A4'
  )
)
Related