Quick tip - Coercing subdomains in Rails
Are you using subdomains as account keys or the account location plugin? I recently worked on a project where this scheme was in place and had to come up with a way to change the subdomain for app specific functions as opposed to account specific ones. For this particular app the user can navigate to other subdomains and to site specific pages. In these cases I wanted to coerce the subdomain which rails does not easily allow using the link_to, redirect_to, and url_for methods.
Here is the problem:
# current url: sally.example.com/stuff
link_to :controller => 'site'
# you want this => http://www.example.com
# you get this => http://sally.example.com
So I monkey-patched url_for so you can do:
# current url: sally.example.com/stuff
link_to :controller => 'site', :overwrite_subdomain => 'www'
# => http://www.example.com
action_controller_ext.rb
module ActionController
class Base
alias_method :old_url_for, :url_for
def url_for(options = {}, *parameters_for_method_reference)
if options.is_a?(Hash) && options.keys.include?(:overwrite_subdomain)
options[:only_path] = false
new_subdomain = options.delete(:overwrite_subdomain)
current_subdomain = request.host_with_port.split('.')[0]
@url.rewrite(rewrite_options(options)).sub(current_subdomain, new_subdomain)
else
if parameters_for_method_reference.empty?
old_url_for(options)
else
old_url_for(options, parameters_for_method_reference)
end
end
end
end
end
environment.rb
require 'action_controller_ext.rb'


Commenting is closed for this article.