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

Quality arguments to Accept header should default to 1.0 #2366

Merged
merged 8 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
2 changes: 1 addition & 1 deletion lib/grape/middleware/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def mime_array
vendor_prefix_pattern = /vnd\.[^+]+\+/

accept.scan(accept_into_mime_and_quality)
.sort_by { |_, quality_preference| -quality_preference.to_f }
.sort_by { |_, quality_preference| -(quality_preference || '1.0').to_f }
hiddewie marked this conversation as resolved.
Show resolved Hide resolved
.flat_map { |mime, _| [mime, mime.sub(vendor_prefix_pattern, '')] }
end
end
Expand Down
11 changes: 11 additions & 0 deletions spec/grape/middleware/formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -125,15 +125,26 @@ def to_xml
it 'uses quality rankings to determine formats' do
subject.call('PATH_INFO' => '/info', 'HTTP_ACCEPT' => 'application/json; q=0.3,application/xml; q=1.0')
expect(subject.env['api.format']).to eq(:xml)

subject.call('PATH_INFO' => '/info', 'HTTP_ACCEPT' => 'application/json; q=1.0,application/xml; q=0.3')
expect(subject.env['api.format']).to eq(:json)
end

it 'handles quality rankings mixed with nothing' do
subject.call('PATH_INFO' => '/info', 'HTTP_ACCEPT' => 'application/json,application/xml; q=1.0')
expect(subject.env['api.format']).to eq(:json)

subject.call('PATH_INFO' => '/info', 'HTTP_ACCEPT' => 'application/xml; q=1.0,application/json')
expect(subject.env['api.format']).to eq(:xml)
end

it 'handles quality rankings that have a default 1.0 value' do
subject.call('PATH_INFO' => '/info', 'HTTP_ACCEPT' => 'application/json,application/xml;q=0.5')
expect(subject.env['api.format']).to eq(:json)
subject.call('PATH_INFO' => '/info', 'HTTP_ACCEPT' => 'application/xml;q=0.5,application/json')
expect(subject.env['api.format']).to eq(:json)
end

it 'parses headers with other attributes' do
subject.call('PATH_INFO' => '/info', 'HTTP_ACCEPT' => 'application/json; abc=2.3; q=1.0,application/xml; q=0.7')
expect(subject.env['api.format']).to eq(:json)
Expand Down