Last active
November 18, 2020 17:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
awesome, thanks
I've taken the liberty of pulling this into a Gem to for everyone to use: https://github.com/WeAreFarmGeek/tld_length
@toolmantim @johnhamelink you guys are the best, this is so useful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the unknowing ones (like me):
lib/rack/host_based_tld_length.rb
config.middleware.use Rack::HostBasedTldLength, /xip\.io/, 5
to yourconfig/development.rb
Thanks for this nice piece of code! 👍