Rails avoids HTML in my text messages

I use rails 3.2.5 ActionMailerto send text messages. Since I have a mailbox:

message_from_user.text.erb:

Hi <%= @recipient.name %>,

You got the following message from <%= @sender.name %>:

<%= @message %>

If @message- "quotes & ampersands", then the text message contains &quot;quotes &amp; ampersands&quot;. Thus, it seems that rails simply see this as an HTML representation and avoid any html to prevent cross-site scripting. However, this is plain text mail. The extension .text.erbboth ActionMailerdetects this and sets MIME to text/plain. Therefore, I never want to hide any html.

I have a lot of email templates in my application, all of them are simple. I would like to consider fixing them to include <%=raw @message%>or <%= @message.html_safe %>bad style - not very DRY.

I tried various jobs that included money fixing Erubis. None of them seem to work. I am looking for some patch or config parameter or something to disable escaping html for all files .text.erb.

Any help is much appreciated!

+5
source share
2 answers

After hours of debugging through Erubis code, I found the following fix. You can just put it in config/initializers/fix_my_mails.rb. I checked this with rails 3.2.7. It can work with other versions.

module ActionView
  class Template
    module Handlers
      class ERB
        def call(template)
          if template.source.encoding_aware?
            # First, convert to BINARY, so in case the encoding is
            # wrong, we can still find an encoding tag
            # (<%# encoding %>) inside the String using a regular
            # expression
            template_source = template.source.dup.force_encoding("BINARY")

            erb = template_source.gsub(ENCODING_TAG, '')
            encoding = $2

            erb.force_encoding valid_encoding(template.source.dup, encoding)

            # Always make sure we return a String in the default_internal
            erb.encode!
          else
            erb = template.source.dup
          end

          self.class.erb_implementation.new(
            erb,
            :trim => (self.class.erb_trim_mode == "-"),
            :escape => template.identifier =~ /\.text/ # only escape HTML templates
          ).src
        end
      end
    end
  end
end

It simply disables HTML objects in every erb file that contains .textthe file name.

+7
source

All Articles