Skip to content

Instantly share code, notes, and snippets.

@gmontard
Last active October 20, 2023 21:44
Show Gist options
  • Save gmontard/10640733 to your computer and use it in GitHub Desktop.
Save gmontard/10640733 to your computer and use it in GitHub Desktop.
Rails dynamic domain and subdomain routes constraint
# -*- encoding : utf-8 -*-
class Domain < ActiveRecord::Base
after_save :reload_routes
def reload_routes
if self.domain_changed?
REDIS.set("rails_routes_ts", "expired")
end
end
end
# -*- encoding : utf-8 -*-
require 'subdomain'
scope :module => :lms do
constraints(DomainConstraint.new) do
#my routes
end
end
# -*- encoding : utf-8 -*-
class DomainConstraint
STATIC_DOMAINS = %w{ vodeclic.com vodeclic.net vodeclic.dev }
STATIC_SUB_DOMAINS = %w{ lms biblio ip c2i epn archimed }
RESERVED_SUB_DOMAINS = %w{ www business app }
def initialize
generate_hosts
end
def generate_hosts
dynamic_domains = Domain.select("DISTINCT domain").map(&:domain).uniq
sanitized_dynamic_domains = dynamic_domains - domains_for(STATIC_DOMAINS, RESERVED_SUB_DOMAINS)
domains = domains_for(STATIC_DOMAINS, STATIC_SUB_DOMAINS) | sanitized_dynamic_domains
@hosts = domains | domains_for(domains, ["mobile"])
set_timestamp
end
def set_timestamp
REDIS.set("rails_routes_ts", Digest::MD5.hexdigest(@hosts.inspect))
rescue
warn "WARNING - Error in set_timestamp method, maybe redis is down? (method:#{__method__} in #{__FILE__}"
end
def matches?(request)
check_if_expired_routes?
@hosts.include?(request.host)
rescue
warn "WARNING - Error detecting Route auth for current domain #{request.host} (method:#{__method__} in #{__FILE__}"
false
end
def domains_for(domains, subdomains)
subdomains.product(domains).map{ |domain| domain.join "." }
end
def check_if_expired_routes?
if REDIS.get("rails_routes_ts") != Digest::MD5.hexdigest(@hosts.inspect)
generate_hosts
end
rescue
warn "WARNING - Error in check_if_expired_routes? method, maybe redis is down? (method:#{__method__} in #{__FILE__}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment