Action Mailer:如何在存储在数据库中的电子邮件正文中呈现动态数据?

cas*_*yin 4 ruby-on-rails actionmailer

我有Action Mailer设置来使用我的电子邮件模型的body属性(在数据库中)呈现电子邮件.我希望能够在身体中使用erb,但我无法弄清楚如何在发送的电子邮件中呈现它.

我可以使用此代码将正文作为字符串

# 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
Run Code Online (Sandbox Code Playgroud)

我看到这篇文章http://rails-nutshell.labs.oreilly.com/ch05.html说我可以使用,render但我只能render :text上班而不是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
Run Code Online (Sandbox Code Playgroud)

更新:有人建议initialize_template_class在此主题上使用http://www.ruby-forum.com/topic/67820.我现在有这个body

body          :msg => initialize_template_class(:user => user).render(:inline => email.body)
Run Code Online (Sandbox Code Playgroud)

它有效,但我不明白这一点,所以我尝试研究私有方法,并没有太多的东西让我担心这是一个黑客,可能有更好的方法. 建议?

trc*_*den 6

在rails 3.2中:内联渲染方法工作得很好.

  mail(:to => "someemail@address.com",
       :subject => "test") do |format|
    format.text { render :inline => text_erb_content }
    format.html { render :inline => html_erb_content }
  end
Run Code Online (Sandbox Code Playgroud)


Tim*_*ite 5

即使你最终无法使用render:inline,你也可以自己实例化ERb.

  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.
Run Code Online (Sandbox Code Playgroud)