Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

wicked pdf - Extending view to generate PDF returns error after upgrade to Rails 6.1

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'
  )
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...