Rendering a Rails view from within a Sidekiq Worker

痴心易碎 提交于 2021-02-07 08:20:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!