Class: Jsapi::Media::Type
- Inherits:
-
Object
- Object
- Jsapi::Media::Type
- Includes:
- Comparable, TypeAndSubtype
- Defined in:
- lib/jsapi/media/type.rb
Overview
Represents a media type.
Constant Summary collapse
- APPLICATION_JSON =
The
"application/json"media type. Type.new('application', 'json')
- APPLICATION_JSON_SEQ =
The
"application/json-seq"media type. Type.new('application', 'json-seq')
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
otherbytypeandsubtype. -
#json? ⇒ Boolean
Returns true if it represents a JSON media type as specified by mimesniff.spec.whatwg.org/#json-mime-type.
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.
22 23 24 25 26 27 |
# File 'lib/jsapi/media/type.rb', line 22 def from(value) media_type = try_from(value) return media_type unless media_type.nil? raise ArgumentError, "invalid media type: #{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.
31 32 33 34 35 36 |
# File 'lib/jsapi/media/type.rb', line 31 def try_from(value) return value if value.is_a?(Type) 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 type and subtype.
49 50 51 52 53 54 55 56 |
# File 'lib/jsapi/media/type.rb', line 49 def <=>(other) return unless other.is_a?(self.class) result = type <=> other.type return result unless result.zero? subtype <=> other.subtype end |
#json? ⇒ Boolean
Returns true if it represents a JSON media type as specified by mimesniff.spec.whatwg.org/#json-mime-type.
60 61 62 63 |
# File 'lib/jsapi/media/type.rb', line 60 def json? (type.in?(%w[application text]) && subtype == 'json') || subtype.end_with?('+json') end |