Class: HTTP::ContentType

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

Overview

Parsed representation of a Content-Type header

Constant Summary collapse

MIME_TYPE_RE =

Pattern for extracting MIME type from Content-Type header

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

Pattern for extracting charset from Content-Type header

/;\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:

  • mime_type (String, nil) (defaults to: nil)

    MIME type

  • charset (String, nil) (defaults to: nil)

    character set



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:

  • (String, nil)


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:

  • (String, nil)


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:

  • str (String)

    content type header value

Returns:



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 (Array<Symbol>, nil)

    keys to extract, or nil for all

Returns:

  • (Hash{Symbol => Object})


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