For a long time there was no way to generate a URL within an ActionMailer. If you wanted to send a registration email when a user signs up for your application you would have had to pass in the url to be included in the email:
class MyController < ApplicationController
def register
# .. registration logic ...
UserMailer.deliver_registration(user, home_url)
end
end
class UserMailer < ActionMailer::Base
def registration(user, url)
@body = { 'user' => user, 'home' => url }
end
end
This is hardly a hack, but it’s not as nice as it could be. It would be nice if the mailer itself could generate the url – or perhaps if the email template itself could generate the url? That day has come with the new ActionController::UrlWriter module.
Just include ActionController::UrlWriter in your mailer and you get access to all the familiar url_for and even the named url methods (home_url in this example):
class UserMailer < ActionMailer::Base
include ActionController::UrlWriter
def registration(user)
@body = { 'user' => user, 'home' => home_url }
end
end