Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added optional predicate

  • Loading branch information...
commit 69c3a35d7878d6f1d32d89bece081f277f7bbed8 1 parent d5f4c74
@ml ml authored
Showing with 46 additions and 10 deletions.
  1. +34 −10 lib/rack/www.rb
  2. +12 −0 test/www_test.rb
View
44 lib/rack/www.rb
@@ -11,24 +11,48 @@ def initialize(app, options = {})
@redirect = @options[:www] if @options[:www] != nil
@message = @options[:message]
@subdomain = @options[:subdomain]
+ @predicate = @options[:predicate]
end
def call(env)
- if (already_subdomain?(env) && @redirect) || (!already_subdomain?(env) && !@redirect)
- @app.call(env)
+ if redirect?(env)
+ redirect(env)
else
- url = prepare_url(env)
- headers = {"Content-Type" => "text/html", "location" => url}
- if @message.respond_to?(:each)
- message = @message
- else
- message = [@message || '']
- end
- [301, headers, message]
+ @app.call(env)
end
end
private
+
+ def redirect(env)
+ url = prepare_url(env)
+ headers = {"Content-Type" => "text/html", "location" => url}
+
+ if @message.respond_to?(:each)
+ message = @message
+ else
+ message = [@message || '']
+ end
+ [301, headers, message]
+ end
+
+ def redirect?(env)
+ predicate?(env) && change_subdomain?(env)
+ end
+
+ def predicate?(env)
+ if @predicate
+ @predicate.call env
+ else
+ true
+ end
+ end
+
+ def change_subdomain?(env)
+ @redirect && !already_subdomain?(env) ||
+ !@redirect && already_subdomain?(env)
+ end
+
def already_subdomain?(env)
env["HTTP_HOST"].downcase =~ /^(#{@subdomain}.)/
end
View
12 test/www_test.rb
@@ -81,4 +81,16 @@ class WWW < TestWWW
assert_equal "http://www.example.com/",
last_response.headers['Location']
end
+
+ test "predicate returning false" do
+ self.app = Rack::WWW.new(default_app, :predicate => lambda { |env| false } )
+ get "http://example.com/"
+ assert_equal last_response.status, 200
+ end
+
+ test "predicate returning true" do
+ self.app = Rack::WWW.new(default_app, :predicate => lambda { |env| true } )
+ get "http://example.com/"
+ assert_equal "http://www.example.com/", last_response.headers['Location']
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.