I'm using the following set of code in both my views and the mailer:
<%= simple_format(auto_link(h(user_input))) %>
I begin by calling html_safe (h) on the user_input, in order to escape any dangerous code. I then call auto_link to enable any links in their input, and then I call simple_format to enable line breaks and such.
This works perfectly in my view, and properly displays the following, fully escaped, yet with a working link:
" http://google.com "
However, when the exact same is displayed in an ActionMailer email, I'm seeing all of the special characters, including my autolink, doubly escaped (the &quot;
for example doesn't display correctly as a result) :
&quot; <a href=3D"http://google.com">http://google.=com</a> &quot;
For some reason, I need to re-mark it as html_safe again to get it working:
<%= simple_format(auto_link(h(user_input))).html_safe %>
This correctly outputs:
" <a href=3D"http://google.com">http://google.com</a> "
Any ideas on why ActionView and ActionMailer treat the same code differently?
Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from ActionMailer::Base and live in app/mailers. Those mailers have associated views that appear alongside controller views in app/views. 2 Sending Emails
This has been deprecated in Rails 3.0 in favour of just calling the method name itself. Sending out an email should only take a fraction of a second, but if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
When you call the mail method now, Action Mailer will detect the two templates (text and HTML) and automatically generate a multipart/alternative email. Mailers are really just another way to render a view. Instead of rendering a view and sending it over the HTTP protocol, they are sending it out through the email protocols instead.
The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the welcome_email method will be in app/views/user_mailer/welcome_email.html.erb for the HTML version and welcome_email.text.erb for the plain text version.
If you call simple_format from the email template (to render out line breaks), the behavior you get is terribly unusual, and it turns out this helper is overwritten with a private method.
Anyways, you can access simple_format in the email template by using this hack:
ApplicationController.helpers.simple_format()
Hopefully in another rails release this will be fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With