From 051581fe2e2b7cbca53b5ce9b81a64b018296739 Mon Sep 17 00:00:00 2001 From: Robert Keresnyei Date: Tue, 9 Jul 2024 19:04:37 +0200 Subject: [PATCH] Evaluate host block only if needed --- lib/rack/canonical_host.rb | 9 +-------- lib/rack/canonical_host/redirect.rb | 12 +++++++++--- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/lib/rack/canonical_host.rb b/lib/rack/canonical_host.rb index 91f4605..f5d0210 100644 --- a/lib/rack/canonical_host.rb +++ b/lib/rack/canonical_host.rb @@ -17,8 +17,7 @@ def call(env) return request.bad_request_response unless request.valid? - host = evaluate_host(env) - redirect = Redirect.new(env, host, options) + redirect = Redirect.new(env, host, options, &block) if redirect.canonical? app.call(env) @@ -33,11 +32,5 @@ def call(env) attr_accessor :host attr_accessor :options attr_accessor :block - - private - - def evaluate_host(env) - block and block.call(env) or host - end end end diff --git a/lib/rack/canonical_host/redirect.rb b/lib/rack/canonical_host/redirect.rb index 757de9e..ed84761 100644 --- a/lib/rack/canonical_host/redirect.rb +++ b/lib/rack/canonical_host/redirect.rb @@ -15,12 +15,13 @@ class Redirect HTML - def initialize(env, host, options={}) + def initialize(env, host, options={}, &block) self.env = env self.host = host self.ignore = Array(options[:ignore]) self.conditions = Array(options[:if]) self.cache_control = options[:cache_control] + self.block = block end def canonical? @@ -39,6 +40,7 @@ def response attr_accessor :ignore attr_accessor :conditions attr_accessor :cache_control + attr_accessor :block private @@ -74,15 +76,19 @@ def ignored? end def known? - host.nil? || request_uri.host == host + evaluated_host.nil? || request_uri.host == evaluated_host end def new_url uri = request_uri.dup - uri.host = host + uri.host = evaluated_host uri.normalize.to_s end + def evaluated_host + @evaluated_host ||= block and block.call(env) or host + end + def request_uri @request_uri ||= Addressable::URI.parse(Rack::Request.new(env).url) end