Class: Datadog::AppSec::Utils::HTTP::MediaType

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/appsec/utils/http/media_type.rb

Overview

Implementation of media type for content negotiation

See:

Defined Under Namespace

Classes: ParseError

Constant Summary collapse

WILDCARD =
'*'
TOKEN_RE =
/[-#$%&'*+.^_`|~A-Za-z0-9]+/.freeze
PARAMETER_RE =
%r{ # rubocop:disable Style/RegexpLiteral
  (?:
    (?<parameter_name>#{TOKEN_RE})
    =
    (?:
      (?<parameter_value>#{TOKEN_RE})
      |
      "(?<parameter_value>[^"]+)"
    )
  )
}ix.freeze
MEDIA_TYPE_RE =
%r{
  \A
  (?<type>#{TOKEN_RE})/(?<subtype>#{TOKEN_RE})
  (?<parameters>
    (?:
      \s*;\s*
      #{PARAMETER_RE}
    )*
  )
  \Z
}ix.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(media_type) ⇒ MediaType

Returns a new instance of MediaType.

Raises:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 49

def initialize(media_type)
  media_type_match = MEDIA_TYPE_RE.match(media_type)

  raise ParseError, media_type.inspect if media_type_match.nil?

  @type = (media_type_match['type'] || WILDCARD).downcase
  @subtype = (media_type_match['subtype'] || WILDCARD).downcase
  @parameters = {}

  parameters = media_type_match['parameters']

  return if parameters.nil?

  parameters.split(';').map(&:strip).each do |parameter|
    parameter_match = PARAMETER_RE.match(parameter)

    next if parameter_match.nil?

    parameter_name = parameter_match['parameter_name']
    parameter_value = parameter_match['parameter_value']

    next if parameter_name.nil? || parameter_value.nil?

    @parameters[parameter_name.downcase] = parameter_value.downcase
  end
end

Instance Attribute Details

#parametersObject (readonly)

Returns the value of attribute parameters.



47
48
49
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 47

def parameters
  @parameters
end

#subtypeObject (readonly)

Returns the value of attribute subtype.



47
48
49
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 47

def subtype
  @subtype
end

#typeObject (readonly)

Returns the value of attribute type.



47
48
49
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 47

def type
  @type
end

Instance Method Details

#to_sObject



76
77
78
79
80
81
82
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 76

def to_s
  s = +"#{@type}/#{@subtype}"

  s << ';' << @parameters.map { |k, v| "#{k}=#{v}" }.join(';') if @parameters.count > 0

  s
end