Class: HTTPX::ContentType

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

Overview

Helper class which decodes the HTTP "content-type" header.

Constant Summary collapse

MIME_TYPE_RE =

Returns:

  • (Regexp)
%r{^([^/]+/[^;]+)(?:$|;)}.freeze
CHARSET_RE =

Returns:

  • (Regexp)
/;\s*charset=([^;]+)/i.freeze

Instance Method Summary collapse

Constructor Details

#initialize(header_value) ⇒ ContentType

Returns a new instance of ContentType.

Parameters:

  • header_value (String, nil)


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

def initialize(header_value)
  @header_value = header_value
  @mime_type = @charset = nil
  @initialized = false
end

Instance Method Details

#charsetString?

returns the charset declared in the header.

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

Returns:

  • (String, nil)


242
243
244
245
246
247
248
# File 'lib/httpx/response.rb', line 242

def charset
  return @charset if @initialized

  load

  @charset
end

#loadvoid

This method returns an undefined value.



252
253
254
255
256
257
258
259
260
# File 'lib/httpx/response.rb', line 252

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

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

  @initialized = true
end

#mime_typeString?

returns the mime type declared in the header.

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

Returns:

  • (String, nil)


230
231
232
233
234
235
236
# File 'lib/httpx/response.rb', line 230

def mime_type
  return @mime_type if @initialized

  load

  @mime_type
end