Class: HTTP::ContentType

Inherits:
Object
  • Object
show all
Defined in:
lib/http/content_type.rb,
sig/http.rbs

Overview

Parsed representation of a Content-Type header

Constant Summary collapse

MIME_TYPE_RE =

Pattern for extracting MIME type from Content-Type header

Returns:

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

Pattern for extracting charset from Content-Type header

Returns:

/;\s*charset=([^;]+)/i

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mime_type = nil, charset = nil) ⇒ ContentType

Create a new ContentType instance

Examples:

HTTP::ContentType.new("text/html", "utf-8")

Parameters:

  • (defaults to: nil)

    MIME type

  • (defaults to: nil)

    character set

API:

  • public



68
69
70
71
# File 'lib/http/content_type.rb', line 68

def initialize(mime_type = nil, charset = nil)
  @mime_type = mime_type
  @charset   = charset
end

Instance Attribute Details

#charsetString?

Character set of the content

Examples:

content_type.charset # => "utf-8"

Returns:

API:

  • public



27
28
29
# File 'lib/http/content_type.rb', line 27

def charset
  @charset
end

#mime_typeString?

MIME type of the content

Examples:

content_type.mime_type # => "text/html"

Returns:

API:

  • public



18
19
20
# File 'lib/http/content_type.rb', line 18

def mime_type
  @mime_type
end

Class Method Details

.parse(str) ⇒ ContentType

Parse string and return ContentType object

Examples:

HTTP::ContentType.parse("text/html; charset=utf-8")

Parameters:

  • content type header value

Returns:

API:

  • public



38
39
40
# File 'lib/http/content_type.rb', line 38

def parse(str)
  new mime_type(str), charset(str)
end

Instance Method Details

#deconstruct_keys(keys) ⇒ Hash{Symbol => Object}

Pattern matching interface for matching against content type attributes

Examples:

case response.content_type
in { mime_type: /json/ }
  "JSON content"
end

Parameters:

  • keys to extract, or nil for all

Returns:

API:

  • public



84
85
86
87
# File 'lib/http/content_type.rb', line 84

def deconstruct_keys(keys)
  hash = { mime_type: @mime_type, charset: @charset }
  keys ? hash.slice(*keys) : hash
end