简体   繁体   中英

How to use a helper in a view that has been called by a Rails sidekiq worker?

I am backgrounding an automated reporting process through the use of a Sidekiq worker; however, the views call some methods that are defined within helpers, but cannot access them because the helpers are not available when called via a Sidekiq worker.

How can I accomplish this? Here's an example of what I have going on:

# app/helpers/report_helper.rb

def random_uuid_method
  return SecureRandom.hex(10)
end
# app/workers/sidekiq/report_generator_worker.rb

class ReportGeneratorWorker
    include Sidekiq::Worker
    sidekiq_options queue: Rails.env.to_sym
    
    def perform
        ac_base = ActionController::Base.new()
        body_html = ac_base.render_to_string template: 'common/report_templates/generate_pdf.html.erb', layout: false
    end
end

# app/views/common/report_templates/generate_pdf.html.erb

Here's your UUID: <%= random_uuid_method %>

This is just an example. I understand that SecureRandom.hex(10) in a normal case scenario could just be directly called from within the view, but I am trying to access the methods defined within a worker. When I do this, I get an error in the console telling me that random_uuid_method is an undefined method.

Try using Application Controller directly instead. Like this:

app_controller = ApplicationController.new
body_html = app_controller.render_to_string template: 'common/report_templates/generate_pdf.html.erb', layout: false

The difference is that ActionController::Base does not include helpers, ApplicationController on the other hand does include them

尝试包含它们 ApplicationHelper 或 ReportHelper

ac_base.class.include ApplicationHelper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM