Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add Rack::ContentType middleware

Signed-off-by: Ryan Tomayko <rtomayko@gmail.com>
  • Loading branch information...
commit fbb2ae41992fe609c0d004f13605ad0f8fc46c81 1 parent 91cea70
@candlerb candlerb authored rtomayko committed
View
1  lib/rack.rb
@@ -31,6 +31,7 @@ def self.release
autoload :CommonLogger, "rack/commonlogger"
autoload :ConditionalGet, "rack/conditionalget"
autoload :ContentLength, "rack/content_length"
+ autoload :ContentType, "rack/content_type"
autoload :File, "rack/file"
autoload :Deflater, "rack/deflater"
autoload :Directory, "rack/directory"
View
23 lib/rack/content_type.rb
@@ -0,0 +1,23 @@
+require 'rack/utils'
+
+module Rack
+
+ # Sets the Content-Type header on responses which don't have one.
+ #
+ # Builder Usage:
+ # use Rack::ContentType, "text/plain"
+ #
+ # When no content type argument is provided, "text/html" is assumed.
+ class ContentType
+ def initialize(app, content_type = "text/html")
+ @app, @content_type = app, content_type
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers = Utils::HeaderHash.new(headers)
+ headers['Content-Type'] ||= @content_type
+ [status, headers.to_hash, body]
+ end
+ end
+end
View
30 test/spec_rack_content_type.rb
@@ -0,0 +1,30 @@
+require 'rack/mock'
+require 'rack/content_type'
+
+context "Rack::ContentType" do
+ specify "sets Content-Type to default text/html if none is set" do
+ app = lambda { |env| [200, {}, "Hello, World!"] }
+ status, headers, body = Rack::ContentType.new(app).call({})
+ headers['Content-Type'].should.equal 'text/html'
+ end
+
+ specify "sets Content-Type to chosen default if none is set" do
+ app = lambda { |env| [200, {}, "Hello, World!"] }
+ status, headers, body =
+ Rack::ContentType.new(app, 'application/octet-stream').call({})
+ headers['Content-Type'].should.equal 'application/octet-stream'
+ end
+
+ specify "does not change Content-Type if it is already set" do
+ app = lambda { |env| [200, {'Content-Type' => 'foo/bar'}, "Hello, World!"] }
+ status, headers, body = Rack::ContentType.new(app).call({})
+ headers['Content-Type'].should.equal 'foo/bar'
+ end
+
+ specify "case insensitive detection of Content-Type" do
+ app = lambda { |env| [200, {'CONTENT-Type' => 'foo/bar'}, "Hello, World!"] }
+ status, headers, body = Rack::ContentType.new(app).call({})
+ headers.to_a.select { |k,v| k.downcase == "content-type" }.
+ should.equal [["CONTENT-Type","foo/bar"]]
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.