Skip to content

Commit c61a661

Browse files
committed
Merge branch 'accept_format_parameter' of git://github.com/neetiraj/grape into accept_format_parameter
2 parents 62f70cc + 9708c56 commit c61a661

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

lib/grape/middleware/formatter.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def headers
1919
end
2020

2121
def before
22-
fmt = format_from_extension || options[:format] || format_from_header || options[:default_format]
22+
fmt = format_from_extension || format_from_params || options[:format] || format_from_header || options[:default_format]
2323
if content_types.key?(fmt)
2424
if !env['rack.input'].nil? and (body = env['rack.input'].read).strip.length != 0
2525
parser = parser_for fmt
@@ -50,6 +50,15 @@ def format_from_extension
5050
nil
5151
end
5252

53+
def format_from_params
54+
if env['QUERY_STRING']
55+
format_query = env['QUERY_STRING'].split('&').reject{|q| !q.include?('format=')}
56+
return format_query[0].split('=').last.to_sym if (format_query && !format_query.empty?)
57+
else
58+
nil
59+
end
60+
end
61+
5362
def format_from_header
5463
mime_array.each do |t|
5564
if mime_types.key?(t)

spec/grape/middleware/formatter_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,13 @@ def to_xml
8080
subject.env['api.format'].should == :json
8181
end
8282

83+
it 'should use the format parameter if one is provided' do
84+
subject.call({'PATH_INFO' => '/somewhere','QUERY_STRING' => 'format=json'})
85+
subject.env['api.format'].should == :json
86+
subject.call({'PATH_INFO' => '/somewhere','QUERY_STRING' => 'format=xml'})
87+
subject.env['api.format'].should == :xml
88+
end
89+
8390
it 'should use the default format if none is provided' do
8491
subject.call({'PATH_INFO' => '/info'})
8592
subject.env['api.format'].should == :txt

0 commit comments

Comments
 (0)