From d49576d4e9e135b659f369de4618394d3c9b4120 Mon Sep 17 00:00:00 2001 From: Blake Mizerany Date: Fri, 23 Nov 2007 18:02:29 -0800 Subject: [PATCH] format --- lib/sinatra.rb | 26 +++++++++++++++++++------- test/dispatching_test.rb | 20 ++++++++++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/lib/sinatra.rb b/lib/sinatra.rb index 9cb1c47..e66a749 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -65,7 +65,11 @@ end module Sinatra extend self - EventContext = Struct.new(:request, :response) do + EventContext = Struct.new(:request, :response, :route_params) do + def params + @params ||= request.params.merge(route_params).symbolize_keys + end + def method_missing(name, *args) if args.size == 1 && response.respond_to?("#{name}=") response.send("#{name}=", args.first) @@ -109,7 +113,8 @@ module Sinatra :raise_errors => false, :env => :development, :root => File.dirname($0), - :default_static_mime_type => 'text/plain' + :default_static_mime_type => 'text/plain', + :default_params => { :format => 'html' } } end @@ -145,7 +150,7 @@ module Sinatra request.request_method.downcase.to_sym, request.path_info ) - context = EventContext.new(request, response) + context = EventContext.new(request, response, route.params) context.status = nil begin result = context.instance_eval(&route.block) @@ -186,13 +191,19 @@ module Sinatra @param_keys << $1.intern "(#{URI_CHAR}+)" end - @pattern = /^#{regex}$/ + @param_keys << :format + @pattern = /^#{regex}(?:\.(#{URI_CHAR}+))?$/ end def match(path) return nil unless path =~ @pattern - params = @param_keys.zip($~.captures.map(&:from_param)).to_hash - Result.new(@path, @block, params, 200) + params = @param_keys.zip($~.captures.compact.map(&:from_param)).to_hash + Result.new(@path, @block, include_format(params), 200) + end + + def include_format(h) + h.delete(:format) unless h[:format] + Sinatra.config[:default_params].merge(h) end end @@ -208,7 +219,8 @@ module Sinatra def default_status @code end - + + def params; {}; end end end diff --git a/test/dispatching_test.rb b/test/dispatching_test.rb index f3dc28b..d001d9b 100644 --- a/test/dispatching_test.rb +++ b/test/dispatching_test.rb @@ -90,6 +90,26 @@ context "Dispatching" do body.should.equal "uh oh" status.should.equal 555 end + + specify "should give format for free" do + get '/formatted' do + params[:format].should.equal 'xml' + end + + get_it '/formatted.xml' + + should.be.ok + end + + specify "should give format default html format for free" do + get '/formatted' do + params[:format].should.equal 'html' + end + + get_it '/formatted' + + should.be.ok + end end -- 2.11.4.GIT