Permalink
Browse files

Added Rack::Static middleware.

darcs-hash:20070311134325-111e0-52498bf73acccbc91b95c79f91c3feaa8a8697a7.gz
  • Loading branch information...
chneukirchen committed Mar 11, 2007
1 parent 1d9ee63 commit 2143f5e1a315bd2fad61be641c351f25a406a3a0
Showing with 77 additions and 0 deletions.
  1. +40 −0 lib/rack/static.rb
  2. +37 −0 test/spec_rack_static.rb
View
@@ -0,0 +1,40 @@
+module Rack
+
+ # The Rack::Static middleware intercepts requests for static files
+ # (javascript files, images, stylesheets, etc) based on the url prefixes
+ # passed in the options, and serve them using a Rack::File object. This
+ # allows a Rack stack to serve both static and dynamic content.
+ #
+ # Examples:
+ # use Rack::Static, :urls => ["/media"]
+ # will serve all requests beginning with /media from the "media" folder
+ # located in the current directory (ie media/*).
+ #
+ # use Rack::Static, :urls => ["/css", "/images"], :root => "public"
+ # will serve all requests beginning with /css or /images from the folder
+ # "public" in the current directory (ie public/css/* and public/images/*)
+
+ class Static
+
+ def initialize(app, options={})
+ @app = app
+ @urls = options[:urls] || Array.new
+ @urls << "/favicon.ico"
+ root = options[:root] || Dir.pwd
+ @file_server = Rack::File.new(root)
+ end
+
+ def call(env)
+ path = env["PATH_INFO"]
+ can_serve = @urls.any? { |url| path.index(url) == 0 }
+
+ if can_serve
+ @file_server.call(env)
+ else
+ @app.call(env)
+ end
+ end
+
+ end
+
+end
View
@@ -0,0 +1,37 @@
+require 'test/spec'
+
+require 'rack/static'
+require 'rack/mock'
+
+class DummyApp
+ def call(env)
+ [200, {}, "Hello World"]
+ end
+end
+
+context "Rack::Static" do
+ root = File.expand_path(File.dirname(__FILE__))
+ OPTIONS = {:urls => ["/cgi"], :root => root}
+
+ setup do
+ @request = Rack::MockRequest.new(Rack::Static.new(DummyApp.new, OPTIONS))
+ end
+
+ specify "serves files" do
+ res = @request.get("/cgi/test")
+ res.should.be.ok
+ res.body.should =~ /ruby/
+ end
+
+ specify "404s if url root is known but it can't find the file" do
+ res = @request.get("/cgi/foo")
+ res.should.be.not_found
+ end
+
+ specify "calls down the chain if url root is not known" do
+ res = @request.get("/something/else")
+ res.should.be.ok
+ res.body.should == "Hello World"
+ end
+
+end

0 comments on commit 2143f5e

Please sign in to comment.