Skip to content

Commit 71741d2

Browse files
committed
Clean up lazy block evaluation and add spec
1 parent 126f201 commit 71741d2

3 files changed

Lines changed: 30 additions & 10 deletions

File tree

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
* Lazily evaluate block ([Robert Keresnyei][yenshirak])
6+
37
## 1.3.0 (2024-03-15)
48

59
* Respond to invalid request URL with 400 ([Gareth Jones][G-Rath])
@@ -100,3 +104,4 @@
100104
[olleolleolle]: https://github.com/olleolleolle
101105
[vinnydiehl]: https://github.com/vinnydiehl
102106
[G-Rath]: https://github.com/G-Rath
107+
[yenshirak]: https://github.com/yenshirak

lib/rack/canonical_host/redirect.rb

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class Redirect
1818
def initialize(env, host, options={}, &block)
1919
self.env = env
2020
self.host = host
21+
self.block = block
2122
self.ignore = Array(options[:ignore])
2223
self.conditions = Array(options[:if])
2324
self.cache_control = options[:cache_control]
@@ -37,6 +38,7 @@ def response
3738

3839
attr_accessor :env
3940
attr_accessor :host
41+
attr_accessor :block
4042
attr_accessor :ignore
4143
attr_accessor :conditions
4244
attr_accessor :cache_control
@@ -55,6 +57,17 @@ def any_match?(patterns, request_uri)
5557
}
5658
end
5759

60+
def enabled?
61+
return true if conditions.empty?
62+
63+
any_match?(conditions, request_uri)
64+
end
65+
66+
def evaluated_host
67+
return @evaluated_host if defined?(@evaluated_host)
68+
@evaluated_host = block && block.call(env) || host
69+
end
70+
5871
def headers
5972
{
6073
'cache-control' => cache_control,
@@ -63,12 +76,6 @@ def headers
6376
}.reject { |_, value| !value }
6477
end
6578

66-
def enabled?
67-
return true if conditions.empty?
68-
69-
any_match?(conditions, request_uri)
70-
end
71-
7279
def ignored?
7380
return false if ignore.empty?
7481

@@ -85,10 +92,6 @@ def new_url
8592
uri.normalize.to_s
8693
end
8794

88-
def evaluated_host
89-
@evaluated_host ||= block and block.call(env) or host
90-
end
91-
9295
def request_uri
9396
@request_uri ||= Addressable::URI.parse(Rack::Request.new(env).url)
9497
end

spec/rack/canonical_host_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,18 @@ def call_app
298298
let(:url) { 'http://www.example.com/full/path' }
299299
end
300300
end
301+
302+
context 'with :if option that rejects the request' do
303+
let(:url) { 'http://api.example.com/full/path' }
304+
305+
let(:app) {
306+
build_app(nil, if: ->(uri) { uri.host == 'example.com' }) { raise }
307+
}
308+
309+
it 'does not evaluate the block' do
310+
expect { call_app }.to_not raise_error
311+
end
312+
end
301313
end
302314
end
303315
end

0 commit comments

Comments
 (0)