Tiago Scolari

bits for fun

Complex constraints for rails routes

2012-09-19

It’s possible to use a custom class as a constraint for your routes. For example:

# lib/domain_constraint.rb
class DomainConstraint
  def initialize(domains)
    @domains = Array(domains).flatten
  end

  def matches?(request)
    @domains.include? request.env["SERVER_NAME"]
  end
end

This could be used to match a custom domain in your route:

# config/routes.rb
require 'domain_constraint.rb'

MyApp::Application.routes.draw do
  constraint(DomainConstraint.new('mobile.site.com')) do
    root to: 'mobile#index'
    ...
  end

  constraint(DomainConstraint.new(['site.com', 'www.site.com'])) do
    root to: 'desktop#index'
    ...
  end
end

I found this useful to route for different controllers and matching routes only in the production env:

# domain_constraint.rb
  ...
  def matches?(request)
    Rails.env.production? && @domains.include? request.env["SERVER_NAME"]
  end
  ...

Source: This question from stackoverflow.