[RUBY] Use Rails template function (ERB) other than Controller (Action View)

Overview

Rails is convenient because it links templates with actions. Action View and ERB (Embedded Ruby). Occasionally, you may want to use the template elsewhere. I looked it up, but I didn't get much information, or it didn't work when I thought I found it, so I'll post the solution as a reminder.

Operating environment

ruby 2.6.5 rails 5.2.3

sample

For example, use it in Job.

Create a template under app / views (any location is possible).

ERB:sample.html.erb


<%= user_name %>to

This is a sample.

Next is Job.

send_template_job.rb


class SendTemplateJob < ApplicationJob
  queue_as :default

  def perform(*args)
    #Use template
    content = ActionView::Base.new('app/views').render(file: 'sample',
                                                       locals: { user_name: current_user.name },
                                                       layout: false)
    #Describe the process of sending the character string generated using the template somewhere
    #For example, slack

  end
end

If you write like this, the variable defined as user_name in erb can be expanded and acquired as a character string.

Recommended Posts

Use Rails template function (ERB) other than Controller (Action View)
I want to use the sanitize method other than View.
Rails routing controller view relationship
Rails 5 Code Reading Part 2 ~ Action View ~
Set Rails routing other than id
Definitions other than 7 basic actions in Rails