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 =
Media::Type for
"application/json". Type.new('application', 'json')
- APPLICATION_JSON_SEQ =
Media::Type for
"application/json-seq". Type.new('application', 'json-seq')
- TEXT_PLAIN =
Media::Type for
"text/plain". Type.new('text', 'plain')
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.
25 26 27 28 29 30 |
# File 'lib/jsapi/media/type.rb', line 25 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.
35 36 37 38 39 40 |
# File 'lib/jsapi/media/type.rb', line 35 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.
53 54 55 56 57 58 59 60 |
# File 'lib/jsapi/media/type.rb', line 53 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.
64 65 66 67 |
# File 'lib/jsapi/media/type.rb', line 64 def json? (type.in?(%w[application text]) && subtype == 'json') || subtype.end_with?('+json') end |