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

I get the 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 

You can use the modified url_for in controller views. But I have problems with ActionMailer.

I tried using the following:

 class Notifier < ActionMailer::Base include UrlHelper end 

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

What is the best practice of adding a new url_for

+4
source share
3 answers

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

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

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

 before_filter :set_mailer_url_options 

A source

+5
source

I have a solution to this problem, but I don't think this is the best way to do this. I tried and still try to find a better solution, but here is what I did in my email template. The reason I put this in my email template is because I use Devise, but I hope to come up with something better.

 subdomain = @resource.account.subdomain subdomain = (subdomain || "") subdomain += "." unless subdomain.empty? host = [subdomain, ActionMailer::Base::default_url_options[:host]].join 

You can pass the host to url_for now like

 user_confirmation_url(:host => host) 
+1
source

I found the simplest solution for Rails 3.0.x was to create a host with a subdomain manually in each URL in my email submissions. For instance:

 Your account is here: <%= account_url(:host => "#{@account.subdomain}.#{ActionMailer::Base.default_url_options[:host]}" %> 

- where your @account model knows its subdomain.

It is beautiful and simple, thread safe and isolated. You do not need to pollute other parts of your code base. And it's easy to backtrack as soon as you upgrade to Rails 3.1.x, which should handle all this automatically, I believe.

0
source

All Articles