smallroomsoftware.com

Rails routing based on hostname

Posted on February 10, 2007

Matching a route based on hostname is possible with a few patches to the rails routing code. I followed the advice on Jamis Buck's weblog and patched two methods from my environment.rb:

module ActionController
  module Routing
    class RouteSet
      def extract_request_environment(request)
        { :method => request.method, :hostname => request.domain.split('.').first }
      end
    end
    class Route
      alias_method :old_recognition_conditions, :recognition_conditions
      def recognition_conditions
        result = old_recognition_conditions
        result << "conditions[:hostname] === env[:hostname]" if conditions[:hostname]
        result
      end
    end
  end
end

You can then write routes like:

map.connect '', :controller => 'blah', :action => 'blah', :conditions => {:hostname => 'blah'}

Obviously, you can use a regular expression for the condition argument if you like.

Hosting by site5.com