Action Mailer: how to visualize dynamic data in an email item that is stored in a database?

I have an Action Mailer set up to render email using the body attribute of my email model (in the database). I want to be able to use erb in the body, but I cannot figure out how to display it in the sent email.

I can get the body as a string with this code

# models/user_mailer.rb def custom_email(user, email_id) email = Email.find(email_id) recipients user.email from "Mail It Example < admin@foo.com >" subject "Hello From Mail It" sent_on Time.now # pulls the email body and passes a string to the template views/user_mailer/customer_email.text.html.erb body :msg => email.body end 

I came across this article http://rails-nutshell.labs.oreilly.com/ch05.html which says that I can use render , but I can get render :text to work, not render :inline

 # models/user_mailer.rb def custom_email(user, email_id) email = Email.find(email_id) recipients user.email from "Mail It Example < admin@foo.com >" subject "Hello From Mail It" sent_on Time.now # body :msg => email.body body :msg => (render :text => "Thanks for your order") # renders text and passes as a variable to the template # body :msg => (render :inline => "We shipped <%= Time.now %>") # throws a NoMethodError end 

Update: Someone recommended using initialize_template_class in this thread http://www.ruby-forum.com/topic/67820 >. Now i have this for body

 body :msg => initialize_template_class(:user => user).render(:inline => email.body) 

It works, but I don’t understand it, so I tried to learn a private method, and there isn’t so much that makes me worry that this is a hack, and probably the best way. suggestions

+4
source share
3 answers

Even if you cannot use render: inline, you can always create an ERB yourself.

  require 'erb' x = 42 template = ERB.new <<-EOF The value of x is: <%= x %> EOF puts template.result(binding) #binding here is Kernel::binding, the current variable binding, of which x is a part. 
+5
source

On rails 3.2: the built-in rendering method works very well.

  mail(:to => " someemail@address.com ", :subject => "test") do |format| format.text { render :inline => text_erb_content } format.html { render :inline => html_erb_content } end 
+5
source

Tim's proposal is on the right track. Here's how you implement ERB in action by email

 def custom_email(user, email_id) email = Email.find(email_id) # more email setup ... body :msg => ERB.new(email.body).result(binding) # or ... # body :msg => ERB.new(email.body).result(user.send(:binding)) end 

The difference between the two hashes will determine which erb you use in the body attribute in the database table. With the first you should use <%= user.name %> to access your use. With the second you can just do <%= name %>

+2
source

Source: https://habr.com/ru/post/1308689/


All Articles