Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a Rails view from within a Sidekiq Worker

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.

like image 782
SharkLaser Avatar asked Dec 26 '22 06:12

SharkLaser


2 Answers

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
)
like image 192
infused Avatar answered Dec 28 '22 07:12

infused


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

like image 38
RAJ Avatar answered Dec 28 '22 07:12

RAJ