Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

accept format query parameter like rails to steer the response format #240

Merged
merged 1 commit into from
Sep 23, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/grape/middleware/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def headers
end

def before
fmt = format_from_extension || options[:format] || format_from_header || options[:default_format]
fmt = format_from_extension || format_from_params || options[:format] || format_from_header || options[:default_format]
if content_types.key?(fmt)
if !env['rack.input'].nil? and (body = env['rack.input'].read).strip.length != 0
parser = parser_for fmt
Expand Down Expand Up @@ -50,6 +50,15 @@ def format_from_extension
nil
end

def format_from_params
if env['QUERY_STRING']
format_query = env['QUERY_STRING'].split('&').reject{|q| !q.include?('format=')}
return format_query[0].split('=').last.to_sym if (format_query && !format_query.empty?)
else
nil
end
end

def format_from_header
mime_array.each do |t|
if mime_types.key?(t)
Expand Down
7 changes: 7 additions & 0 deletions spec/grape/middleware/formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ def to_xml
subject.env['api.format'].should == :json
end

it 'should use the format parameter if one is provided' do
subject.call({'PATH_INFO' => '/somewhere','QUERY_STRING' => 'format=json'})
subject.env['api.format'].should == :json
subject.call({'PATH_INFO' => '/somewhere','QUERY_STRING' => 'format=xml'})
subject.env['api.format'].should == :xml
end

it 'should use the default format if none is provided' do
subject.call({'PATH_INFO' => '/info'})
subject.env['api.format'].should == :txt
Expand Down