Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Evaluate host block only if the return value is used #70

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions lib/rack/canonical_host.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
12 changes: 9 additions & 3 deletions lib/rack/canonical_host/redirect.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ class Redirect
</html>
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?
Expand All @@ -39,6 +40,7 @@ def response
attr_accessor :ignore
attr_accessor :conditions
attr_accessor :cache_control
attr_accessor :block

private

Expand Down Expand Up @@ -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
Expand Down