How do I get full URL to an image in a Rails asynchronous mailer?

Chris Aitchison picture Chris Aitchison · Mar 19, 2013 · Viewed 18k times · Source

I want to have emails I send out with ActionMailer contain images that link back to my app. In my development environment, for example:

<img src="http://myfullappurl.dev/assets/myimage.png">

I have this in my development.rb

config.action_controller.asset_host = 'myfullappurl.dev'
config.action_mailer.asset_host = config.action_controller.asset_host
config.action_mailer.default_url_options = { host: 'myfullappurl.dev', only_path: false }

But I can not get my mail templates to render a full URL in any of these way:

asset_path('myimage.png')
asset_path('myimage.png', only_path: false)
image_url('myimage.png')

A lot of similar questions on this topic are answered by doing something like this:

"#{request.protocol}#{request.host_with_port}#{asset_path('image.png')}"

But because my mails are sent asynchronously with Sidekiq, there is no request object like there would be if they were sent synchronously in a controller.

Is there an obvious thing I am missing, or do I have to fight against Rails to do this? I am using Rails 4, but I am sure that anything that works in 3.1/3.2 should do just fine.

Answer

Chris Aitchison picture Chris Aitchison · Mar 21, 2013

Well this is odd behaviour, but I've resolved this issue. It turns out that unless the action_mailer.asset_host starts with http:// then it will be ignored. There is a Regex in actionpack/lib/action_view/helpers/asset_url_helper.rb that defines a valid ActionMailer URI:

URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}

However, if you put a http:// in front of the action_controller.asset_host then you will end up with links to http://http://myfullappurl.dev

So to resolve it I had to add the following to my development.rb

 config.action_controller.asset_host = 'myfullappurl.dev'
 config.action_mailer.asset_host = 'http://myfullappurl.dev'

Just to be clear, this is Rails 4.0.0beta1 with the emails being sent asynchronously with Sidekiq, I am not sure if this affects Rails 3.