Search code examples
ruby-on-railsactionmailer

Rails3: rewrite url_for for subdomain support, how to extend action mailer to use such url_for


I take code from Subdomain RailsCast

module UrlHelper
  def with_subdomain(subdomain)
    subdomain = (subdomain || "")
    subdomain += "." unless subdomain.empty?
    [subdomain, request.domain, request.port_string].join
  end

  def url_for(options = nil)
    if options.kind_of?(Hash) && options.has_key?(:subdomain)
      options[:host] = with_subdomain(options.delete(:subdomain))
    end
    super
  end
end

class ApplicationController < ActionController::Base
  include UrlHelper
end  

It is ok to use modified url_for in views of Controllers. But I have trouble with ActionMailer.

I tried to use following:

class Notifier < ActionMailer::Base
  include UrlHelper
end

But ActionMailer views still use old unmodified url_for from ActionDispatch::Routing::RouteSet.

What is the best practice to add new url_for


Solution

  • Add the following code to the file app/helpers/url_helper.rb:

    def set_mailer_url_options
        ActionMailer::Base.default_url_options[:host] = with_subdomain(request.subdomain)
    end
    

    and modify the file app/controllers/application_controller.rb to add:

    before_filter :set_mailer_url_options
    

    Source