Class: Protocol::Media::Map
- Inherits:
-
Object
- Object
- Protocol::Media::Map
- Defined in:
- lib/protocol/media/map.rb
Overview
A map from concrete media types to objects for range-based lookup.
Class Method Summary collapse
-
.for(entries) ⇒ Object
Convert keyed entries into a media map.
Instance Method Summary collapse
-
#[](media_range) ⇒ Object
Find the object matching a media type or range.
-
#[]=(media_type, object) ⇒ Object
Associate a concrete media type with an object.
-
#for(media_ranges) ⇒ Object
Find the first object matching an ordered sequence of media ranges.
-
#freeze ⇒ Object
Freeze the media map, compiling its entries into an efficient index.
-
#initialize(entries = {}) ⇒ Map
constructor
Initialize a new mutable media map with the given entries.
Constructor Details
#initialize(entries = {}) ⇒ Map
Initialize a new mutable media map with the given entries.
Freezing the map compiles the entries into an efficient immutable index.
29 30 31 32 33 34 35 36 |
# File 'lib/protocol/media/map.rb', line 29 def initialize(entries = {}) @entries = {} @index = nil entries.each do |media_type, object| self[media_type] = object end end |
Class Method Details
.for(entries) ⇒ Object
Convert keyed entries into a media map.
Existing maps are returned unchanged, including their frozen state.
18 19 20 21 22 |
# File 'lib/protocol/media/map.rb', line 18 def self.for(entries) return entries if entries.instance_of?(self) return new(entries).freeze end |
Instance Method Details
#[](media_range) ⇒ Object
Find the object matching a media type or range.
67 68 69 |
# File 'lib/protocol/media/map.rb', line 67 def [](media_range) return lookup(Range.for(media_range)) end |
#[]=(media_type, object) ⇒ Object
Associate a concrete media type with an object.
41 42 43 44 45 46 47 48 |
# File 'lib/protocol/media/map.rb', line 41 def []=(media_type, object) raise FrozenError, "can't modify frozen #{self.class}" if frozen? media_type = Type.for(media_type) @entries[media_type.name] = [media_type, object] @index = nil end |
#for(media_ranges) ⇒ Object
Find the first object matching an ordered sequence of media ranges.
75 76 77 78 79 80 81 82 83 |
# File 'lib/protocol/media/map.rb', line 75 def for(media_ranges) media_ranges.each do |media_range| if object = lookup(Range.for(media_range)) return [object, media_range] end end return nil end |
#freeze ⇒ Object
Freeze the media map, compiling its entries into an efficient index.
52 53 54 55 56 57 58 59 60 61 |
# File 'lib/protocol/media/map.rb', line 52 def freeze return self if frozen? index = self.index @entries = nil index.freeze return super end |