Omid Kamangar
Omid Kamangar

Reputation: 5788

Detect the request domain from the routes.rb file

I have several domains, say foo.com and baz.com, pointing to the same application.
For some of these domains I need to include the locale in the URL, and for other ones the locale should not be present in the URL.
For example, foo.com/en/about would be the same as baz.com/about.

What I thought of, is including something like (:locale) conditionally in the URL, based on the domain.

I wonder if it is possible to detect the domain of the request in the routes.rb file?
For example something like request.domain which is available from a controller, but from the routes.rb file.

Upvotes: 0

Views: 777

Answers (1)

Haider
Haider

Reputation: 254

From the answer https://stackoverflow.com/a/4737007/2018293. You can define a custom constraints class in lib/domain_constraint.rb;

class DomainConstraint
  def initialize(domain)
    @domains = [domain].flatten
  end

  def matches?(request)
    @domains.include? request.domain
  end
end

and then use this in your routes;

constraints DomainConstraint.new('mydomain.com') do
  root :to => 'mydomain#index'
  #other routes for the domain
end

Upvotes: 1

Related Questions