Skip to content

Commit 9708c56

Browse files
Neeti RajNeeti Raj
authored andcommitted
accept format query parameter like rails to steer the response format
1 parent 346fb94 commit 9708c56

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
@@ -68,6 +68,13 @@ def to_xml
6868
subject.env['api.format'].should == :json
6969
end
7070

71+
it 'should use the format parameter if one is provided' do
72+
subject.call({'PATH_INFO' => '/somewhere','QUERY_STRING' => 'format=json'})
73+
subject.env['api.format'].should == :json
74+
subject.call({'PATH_INFO' => '/somewhere','QUERY_STRING' => 'format=xml'})
75+
subject.env['api.format'].should == :xml
76+
end
77+
7178
it 'should use the default format if none is provided' do
7279
subject.call({'PATH_INFO' => '/info'})
7380
subject.env['api.format'].should == :txt

0 commit comments

Comments
 (0)