问题
I have a Sidekiq worker that does some background processing and then finally POSTs a success message to a 3rd party API. This message I post is essentially a "thank you" message and can contain HTML.
In the message I'd like to link back to my site in a properly formatted way. This naturally sounds like a view to me. I'd love to simply use a view template, render it to HTML and finally post it off to the API.
For the life of me, i cannot figure how to render a view from within my Sidekiq worker.
I have considered setting up a dummy controller/view combo and instantiating it from inside the worker but it seems wrong.
Any input would be greatly appreciated.
回答1:
Inside your worker you can use ActionView::Base directly to render a view. For example, to render a users/events
partial:
view = html = ActionView::Base.new(Rails.root.join('app/views'))
view.class.include ApplicationHelper
view.render(
partial: 'users/event',
object: user.events.last
)
回答2:
You can use ERB
for rendering template in your job.
require 'erb'
@text = "my answer" # variables, accessible in template.
template = "This is <%= @text %>."
# you can also render file like ERB.new(File.read(<file name here>))
renderer = ERB.new(template)
puts output = renderer.result()
More about ERB
来源:https://stackoverflow.com/questions/25099926/rendering-a-rails-view-from-within-a-sidekiq-worker