Class: Simple::HTTP::ContentTypeParser

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

Overview

parses content_type to return media_type and charset.

Constant Summary collapse

SPLIT_PATTERN =
%r{\s*[;,]\s*}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content_type) ⇒ ContentTypeParser

Returns a new instance of ContentTypeParser.



23
24
25
26
27
# File 'lib/simple/http/content_type_parser.rb', line 23

def initialize(content_type)
  @content_type = content_type
  @media_type   = content_type.split(SPLIT_PATTERN, 2).first.downcase if content_type
  @charset      = extract_charset_from_content_type if content_type
end

Instance Attribute Details

#charsetObject (readonly)

The charset as embedded on the Content-Type header



21
22
23
# File 'lib/simple/http/content_type_parser.rb', line 21

def charset
  @charset
end

#content_typeObject (readonly)

The content_type value as being passed in.



10
11
12
# File 'lib/simple/http/content_type_parser.rb', line 10

def content_type
  @content_type
end

#media_typeObject (readonly)

The media type (type/subtype) portion of the CONTENT_TYPE header without any media type parameters. e.g., when CONTENT_TYPE is “text/plain;charset=utf-8”, the media-type is “text/plain”.

For more information on the use of media types in HTTP, see: www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7



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

def media_type
  @media_type
end

Instance Method Details

#encodingObject

returns the encoding the body is supposed to be encoded as.



30
31
32
# File 'lib/simple/http/content_type_parser.rb', line 30

def encoding
  resolve_encoding_name(charset || guess_encoding_name)
end

#reencode!(body) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/simple/http/content_type_parser.rb', line 34

def reencode!(body)
  body.force_encoding(encoding)
  unless body.valid_encoding?
    raise "Invalid payload: body is encoded invalid; encoding is #{content_type_parser.encoding.name}"
  end

  body
end