Ruby on Rails route for wildcard subdomains to a controller/action

前端 未结 2 2046
暗喜
暗喜 2021-02-08 14:13

I dynamically create URLs of the form username.users.example.com:

bob.users.example.com
tim.users.example.com
scott.users.example.com
2条回答
  •  南旧
    南旧 (楼主)
    2021-02-08 15:06

    You can constraint route dynamically based on some specific criteria by creating a matches? method

    Lets say we have to filter sub domain of URL

    constraints Subdomain do
      get '*path', to: 'users#show'
    end
    
    class Subdomain
      def self.matches?(request)
        (request.subdomain.present? && request.subdomain.start_with?('.users')
      end
    end
    

    What we are doing here is checking for URL if it start with sub domain users then only hit users#show action. Your class must have mathes? method either class method or instance method. If you want to make it a instance method then do

    constraints Subdomain.new do
      get '*path', to: 'proxy#index'
    end
    

    you can achieve same thing using lambda as well like below.

    Instead of writing class we can also use lambdas

    get '*path', to: 'users#show', constraints: lambda{|request|request.env['SERVER_NAME'].match('.users')}
    

提交回复
热议问题