Skip to content

Instantly share code, notes, and snippets.

@kellysutton
Created March 16, 2012 14:35
Show Gist options
  • Save kellysutton/2050328 to your computer and use it in GitHub Desktop.
Save kellysutton/2050328 to your computer and use it in GitHub Desktop.
ActionMailer assets with hash-based asset hosting

In config/production.rb

  config.action_mailer.asset_host = "https://123123.cloudfront.net"

In config/initializers/mail_image_tag.rb

module ActionView
  # = Action View Asset Tag Helpers
  module Helpers #:nodoc:
    def mail_image_tag(source, options = {})
      options.symbolize_keys!

      if !Rails.env.test? && !Rails.env.development?
        src = options[:src] = ::Rails.application.config.action_mailer.asset_host + "/images/" + source #path_to_image(source)
      else
        src = options[:src] = path_to_image(source)
      end

      unless src =~ /^cid:/
        options[:alt] = options.fetch(:alt){ image_alt(src) }
      end

      if size = options.delete(:size)
        options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
      end

      if mouseover = options.delete(:mouseover)
        options[:onmouseover] = "this.src='#{path_to_image(mouseover)}'"
        options[:onmouseout]  = "this.src='#{src}'"
      end

      tag("img", options)
    end
  end
end

In deploy.rb

  desc "Copy Mailer assets into place (/public/images)"
  task :mailer_assets, :roles => [:web] do
    run "mkdir -p #{current_release}/public/images"
    run "cd #{current_release} && cp app/assets/images/*.* public/images/"
  end

  after   "deploy:assets", "deploy:mailer_assets"

In my email templates

<%= mail_image_tag('asset.png') %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment