SharkLaser
SharkLaser

Reputation: 773

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.

Upvotes: 4

Views: 3332

Answers (2)

infused
infused

Reputation: 24357

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
)

Upvotes: 8

RAJ
RAJ

Reputation: 9747

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

Upvotes: 2

Related Questions