Class: Jsapi::Media::Range
- Inherits:
-
Object
- Object
- Jsapi::Media::Range
- Includes:
- Comparable, TypeAndSubtype
- Defined in:
- lib/jsapi/media/range.rb
Overview
Represents a media range.
Class Method Summary collapse
-
.from(value) ⇒ Object
Transforms
valueto an instance of this class. -
.try_from(value) ⇒ Object
Tries to transform
valueto an instance of this class.
Instance Method Summary collapse
-
#<=>(other) ⇒ Object
Compares it with
otherbypriority. -
#match?(media_type) ⇒ Boolean
Returns true if the given media type matches the media range.
-
#priority ⇒ Object
Returns the level of priority of the media range.
Methods included from TypeAndSubtype
#==, #hash, included, #initialize, #inspect, #to_s
Class Method Details
.from(value) ⇒ Object
Transforms value to an instance of this class.
Raises an ArgumentError when value could not be transformed.
16 17 18 19 20 21 |
# File 'lib/jsapi/media/range.rb', line 16 def from(value) media_range = try_from(value) return media_range unless media_range.nil? raise ArgumentError, "invalid media range: #{value.inspect}" end |
.try_from(value) ⇒ Object
Tries to transform value to an instance of this class. Returns nil if value could not be transformed.
25 26 27 28 29 30 |
# File 'lib/jsapi/media/range.rb', line 25 def try_from(value) return value if value.is_a?(Range) type_and_subtype = pattern.match(value.to_s)&.captures new(*type_and_subtype) if type_and_subtype&.count == 2 end |
Instance Method Details
#<=>(other) ⇒ Object
Compares it with other by priority.
43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/jsapi/media/range.rb', line 43 def <=>(other) return unless other.is_a?(self.class) result = priority <=> other.priority return result unless result.zero? result = type <=> other.type return result unless result.zero? subtype <=> other.subtype end |
#match?(media_type) ⇒ Boolean
Returns true if the given media type matches the media range.
56 57 58 59 60 61 |
# File 'lib/jsapi/media/range.rb', line 56 def match?(media_type) media_type = Type.from(media_type) unless media_type.nil? (type == '*' || type == media_type&.type) && (subtype == '*' || subtype == media_type&.subtype) end |
#priority ⇒ Object
Returns the level of priority of the media range.
64 65 66 |
# File 'lib/jsapi/media/range.rb', line 64 def priority @priority ||= (type == '*' ? 2 : 0) + (subtype == '*' ? 1 : 0) + 1 end |