Skip to content

Commit

Permalink
Allow custom default extention.
Browse files Browse the repository at this point in the history
  • Loading branch information
mynyml authored and rtomayko committed May 21, 2009
1 parent 0e5664a commit 105e4c5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
7 changes: 3 additions & 4 deletions lib/rack/contrib/accept_format.rb
Expand Up @@ -24,18 +24,17 @@ module Rack
# MIT-License - Cyril Rohr
#
class AcceptFormat
# Constants
DEFAULT_EXTENSION = ".html"

def initialize(app)
def initialize(app, default_extention = '.html')
@ext = default_extention
@app = app
end

def call(env)
req = Rack::Request.new(env)
unless req.path_info =~ /(.*)\.(.+)/
accept = env['HTTP_ACCEPT'].to_s.scan(/[^;,\s]*\/[^;,\s]*/)[0].to_s
extension = Rack::Mime::MIME_TYPES.invert[accept] || DEFAULT_EXTENSION
extension = Rack::Mime::MIME_TYPES.invert[accept] || @ext
req.path_info = req.path_info+"#{extension}"
end
@app.call(env)
Expand Down
10 changes: 8 additions & 2 deletions test/spec_rack_accept_format.rb
Expand Up @@ -22,13 +22,19 @@ def mime(ext, type)
specify "should add the default extension if no Accept header" do
request = Rack::MockRequest.env_for("/resource")
body = Rack::AcceptFormat.new(app).call(request).last
body.should == "/resource#{Rack::AcceptFormat::DEFAULT_EXTENSION}"
body.should == "/resource.html"
end

specify "should use custom default extension" do
request = Rack::MockRequest.env_for("/resource")
body = Rack::AcceptFormat.new(app, '.xml').call(request).last
body.should == "/resource.xml"
end

specify "should add the default extension if the Accept header is not registered in the Mime::Types" do
request = Rack::MockRequest.env_for("/resource", 'HTTP_ACCEPT' => 'application/json;q=1.0, text/html;q=0.8, */*;q=0.1')
body = Rack::AcceptFormat.new(app).call(request).last
body.should == "/resource#{Rack::AcceptFormat::DEFAULT_EXTENSION}"
body.should == "/resource.html"
end

specify "should add the correct extension if the Accept header is registered in the Mime::Types" do
Expand Down

0 comments on commit 105e4c5

Please sign in to comment.