From 566e362f1e9c3fbbae7bd1672ae0df52c27e85f4 Mon Sep 17 00:00:00 2001 From: Geoff Buesing Date: Mon, 15 Feb 2010 21:18:47 -0600 Subject: [PATCH] Rack::NotFound: when file path is not specified, a simple Not Found response body is returned --- lib/rack/contrib/not_found.rb | 24 ++++++++++++++++++------ test/spec_rack_not_found.rb | 13 +++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/lib/rack/contrib/not_found.rb b/lib/rack/contrib/not_found.rb index cd0ca8f..056b629 100644 --- a/lib/rack/contrib/not_found.rb +++ b/lib/rack/contrib/not_found.rb @@ -1,18 +1,30 @@ module Rack # Rack::NotFound is a default endpoint. Initialize with the path to - # your 404 page. - + # your 404 page. Example: + # + # run Rack::NotFound.new('public/404.html') + # + # If no file path is specified, a simple "Not Found" response body will be returned. class NotFound F = ::File - def initialize(path) - file = F.expand_path(path) - @content = F.read(file) - @length = @content.size.to_s + def initialize(path = nil) + @content = get_content(path) + @length = Utils.bytesize(@content).to_s end def call(env) [404, {'Content-Type' => 'text/html', 'Content-Length' => @length}, [@content]] end + + private + def get_content(path) + if path + file = F.expand_path(path) + F.read(file) + else + "

Not Found

" + end + end end end diff --git a/test/spec_rack_not_found.rb b/test/spec_rack_not_found.rb index 3a676f9..9cfca69 100644 --- a/test/spec_rack_not_found.rb +++ b/test/spec_rack_not_found.rb @@ -1,4 +1,5 @@ require 'test/spec' +require 'rack/builder' require 'rack/mock' require 'rack/contrib/not_found' @@ -12,6 +13,18 @@ context "Rack::NotFound" do response = Rack::MockRequest.new(app).get('/') response.body.should.equal('Not Found') response.status.should.equal(404) + response['Content-Length'].should.equal('9') + end + + specify "should render simple Not Found response when no file path given" do + app = Rack::Builder.new do + use Rack::Lint + run Rack::NotFound.new + end + response = Rack::MockRequest.new(app).get('/') + response.body.should.equal('

Not Found

') + response.status.should.equal(404) + response['Content-Length'].should.equal('18') end end -- 1.6.3.3