/app/helpers/url_helper.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module UrlHelper
  # adapted from: http://railscasts.com/episodes/221-subdomains-in-rails-3
  def with_subdomain(subdomain)
    subdomain = (subdomain || "")
    subdomain += "." unless subdomain.empty?
    subdomains = request.subdomains.empty? ? "" : (request.subdomains.join(".") + ".")
    [subdomain, subdomains, request.domain].join
  end
  
  def url_for(options = {})
    if options.kind_of?(Hash) && options.has_key?(:subdomain)
      options[:host] = with_subdomain(options.delete(:subdomain))
    end
    super
  end  
end

/spec/helpers/url_helper_spec.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require 'spec_helper'

describe UrlHelper do

  it "should prepend subdomain to standard host" do
    controller.request.host = "example.com"
    helper.url_for(:action => 'index', :subdomain => 'secure').should =~ /^http:\/\/secure.example.com/
  end


  it "should prepend subdomain to hosts with existing subdomains" do
    controller.request.host = "staging.example.com"
    helper.url_for(:action => 'index', :subdomain => 'secure').should =~ /^http:\/\/secure.staging.example.com/
  end

end