Skip to content

Instantly share code, notes, and snippets.

@toolmantim
Last active November 18, 2020 17:23
Show Gist options
  • Save toolmantim/6632690 to your computer and use it in GitHub Desktop.
Save toolmantim/6632690 to your computer and use it in GitHub Desktop.
Reconfigures Rails ActionDispatch's TLD handling dynamically based on the request host, so you don't have to mess with config.action_dispatch.tld_length for cross-device testing using xip.io and friends
# Reconfigures ActionDispatch's TLD handling dynamically based on the request
# host, so you don't have to mess with config.action_dispatch.tld_length for
# cross-device testing using xip.io and friends
#
# Examples:
# use Rack::HostBasedTldLength, /xip\.io/, 5
class Rack::HostBasedTldLength
def initialize(app, host_pattern, host_tld_length)
@app = app
@host_pattern = Regexp.new(host_pattern)
@host_tld_length = host_tld_length
end
def call(env)
original_tld_length = tld_length
request = Rack::Request.new(env)
set_tld_length(@host_tld_length) if request.host =~ @host_pattern
@app.call(env)
ensure
set_tld_length(original_tld_length)
end
private
def tld_length
ActionDispatch::Http::URL.tld_length
end
def set_tld_length(length)
ActionDispatch::Http::URL.tld_length = length
end
end
@coneybeare
Copy link

awesome, thanks

@johnhamelink
Copy link

I've taken the liberty of pulling this into a Gem to for everyone to use: https://github.com/WeAreFarmGeek/tld_length

@catkins
Copy link

catkins commented Oct 30, 2014

@toolmantim @johnhamelink you guys are the best, this is so useful.

@fphilipe
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment