Sha256: af6d0488dc879b5aee1fcddc198b9e7b49b38a8862495e6cb7a03672c7a30bbb

Contents?: true

Size: 1.42 KB

Versions: 2

Compression:

Stored size: 1.42 KB

Contents

require 'apartment/elevators/generic'

module Apartment
  module Elevators
    #   Provides a rack based tenant switching solution based on subdomains
    #   Assumes that tenant name should match subdomain
    #
    class Subdomain < Generic
      def self.excluded_subdomains
        @excluded_subdomains ||= []
      end

      def self.excluded_subdomains=(arg)
        @excluded_subdomains = arg
      end

      def parse_tenant_name(request)
        request_subdomain = subdomain(request.host)

        # If the domain acquired is set to be excluded, set the tenant to whatever is currently
        # next in line in the schema search path.
        tenant = if self.class.excluded_subdomains.include?(request_subdomain)
          nil
        else
          request_subdomain
        end

        tenant.presence
      end

    protected

      # *Almost* a direct ripoff of ActionDispatch::Request subdomain methods

      # Only care about the first subdomain for the database name
      def subdomain(host)
        subdomains(host).first
      end

      #   Assuming tld_length of 1, might need to make this configurable in Apartment in the future for things like .co.uk
      def subdomains(host, tld_length = 1)
        return [] unless named_host?(host)

        host.split('.')[0..-(tld_length + 2)]
      end

      def named_host?(host)
        !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host))
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
apartment-0.23.2 lib/apartment/elevators/subdomain.rb
apartment-0.23.1 lib/apartment/elevators/subdomain.rb