Class: HTTPX::ContentType

Inherits:
Object
  • Object
show all
Defined in:
lib/httpx/response.rb

Overview

Helper class which decodes the HTTP “content-type” header.

Constant Summary collapse

MIME_TYPE_RE =
%r{^([^/]+/[^;]+)(?:$|;)}.freeze
CHARSET_RE =
/;\s*charset=([^;]+)/i.freeze

Instance Method Summary collapse

Constructor Details

#initialize(header_value) ⇒ ContentType

Returns a new instance of ContentType.



201
202
203
# File 'lib/httpx/response.rb', line 201

def initialize(header_value)
  @header_value = header_value
end

Instance Method Details

#charsetObject

returns the charset declared in the header.

ContentType.new("application/json; charset=utf-8").charset #=> "utf-8"
ContentType.new("text/plain").charset #=> nil


219
220
221
222
223
224
# File 'lib/httpx/response.rb', line 219

def charset
  return @charset if defined?(@charset)

  m = @header_value.to_s[CHARSET_RE, 1]
  m && @charset = m.strip.delete('"')
end

#mime_typeObject

returns the mime type declared in the header.

ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"


208
209
210
211
212
213
# File 'lib/httpx/response.rb', line 208

def mime_type
  return @mime_type if defined?(@mime_type)

  m = @header_value.to_s[MIME_TYPE_RE, 1]
  m && @mime_type = m.strip.downcase
end