From 7b8f97233244a0943b952d1bbc1253d3c5d80e7a 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 | 22 +++++++++++++++++----- test/404.html | 2 +- test/spec_rack_not_found.rb | 11 +++++++++++ 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/lib/rack/contrib/not_found.rb b/lib/rack/contrib/not_found.rb index cd0ca8f..391e5b1 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) + def initialize(path = nil) + @content = get_content(path) @length = @content.size.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/404.html b/test/404.html index 8537307..d42454c 100644 --- a/test/404.html +++ b/test/404.html @@ -1 +1 @@ -Not Found \ No newline at end of file +

Not Found

\ No newline at end of file diff --git a/test/spec_rack_not_found.rb b/test/spec_rack_not_found.rb index 3a676f9..b743799 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' @@ -10,6 +11,16 @@ context "Rack::NotFound" do run Rack::NotFound.new('test/404.html') end response = Rack::MockRequest.new(app).get('/') + response.body.should.equal("

Not Found

") + response.status.should.equal(404) + 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) end -- 1.6.1