Skip to content
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: 11 additions & 0 deletions lib/protocol/http/header/accept.rb
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,17 @@ def media_ranges
end
end

# Parse the `accept` header and order media ranges by preference.
#
# Media ranges with equal quality factors retain their original relative order.
#
# @returns [Array(MediaRange)] the preferred media ranges.
def preferred_media_ranges
media_ranges.sort_by.with_index do |media_range, index|
[-media_range.quality_factor, index]
end
end

private

def parse_media_range(value)
Expand Down
4 changes: 4 additions & 0 deletions releases.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Releases

## Unreleased

- Add stable preference ordering for `Accept` media ranges.

## v0.69.0

- Add `Protocol::HTTP::Body::Readable#to_io` for obtaining an IO-compatible stream adapter.
Expand Down
4 changes: 2 additions & 2 deletions test/protocol/http/header/accept.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

describe Protocol::HTTP::Header::Accept do
let(:header) {subject.parse(description)}
let(:media_ranges) {header.media_ranges.sort}
let(:media_ranges) {header.preferred_media_ranges}

with "text/plain, text/html;q=0.5, text/xml;q=0.25" do
it "can parse media ranges" do
Expand Down Expand Up @@ -64,7 +64,7 @@
end

with "text/html, text/plain;q=0.8, text/xml;q=0.6, application/json" do
it "should order based on quality factor" do
it "preserves relative order for equal quality factors" do
expect(media_ranges.collect(&:to_s)).to be == %w{text/html application/json text/plain;q=0.8 text/xml;q=0.6}
end
end
Expand Down
Loading