Skip to content

Instantly share code, notes, and snippets.

@martincik
Forked from tannerburson/subdomains.rb
Created August 27, 2009 09:15
Show Gist options
  • Save martincik/176187 to your computer and use it in GitHub Desktop.
Save martincik/176187 to your computer and use it in GitHub Desktop.
# This method is heavily adapted from the Rails method of determining the subdomain.
require 'rubygems'
require 'sinatra'
require 'rack/request'
# We re-open the request class to add the subdomains method
module Rack
class Request
def subdomains(tld_len=1) # we set tld_len to 1, use 2 for co.uk or similar
# cache the result so we only compute it once.
@env['rack.env.subdomains'] ||= lambda {
# check if the current host is an IP address, if so return an empty array
return [] if (host.nil? ||
/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host))
host.split('.')[0...(1 - tld_len - 2)] # pull everything except the TLD
}.call
end
end
end
get '/' do
@request.subdomains.join("<br/>")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment