Module: WebStruct::Http::Mime

Defined in:
lib/webstruct/http/mime.rb

Overview

Classifies HTTP bodies using Content-Type and light sniffing for ambiguous types.

Constant Summary collapse

MIME_TYPE_MAP =

Exact lowercased MIME subtype to internal type.

{
  "text/html" => :html,
  "application/xhtml+xml" => :xhtml,
  "application/json" => :json,
  "text/json" => :json,
  "text/csv" => :csv,
  "text/tab-separated-values" => :tsv,
  "application/xml" => :xml,
  "text/xml" => :xml,
  "text/plain" => :text
}.freeze

Class Method Summary collapse

Class Method Details

.html_like?(type) ⇒ Boolean

Returns true when type should run HTML-oriented checks (e.g. Shell.detect!).

Parameters:

  • type (Symbol)

Returns:

  • (Boolean)


28
29
30
# File 'lib/webstruct/http/mime.rb', line 28

def html_like?(type)
  %i[html xhtml].include?(type)
end

.normalize(content_type) ⇒ String

Returns the MIME type and subtype in lowercase, without parameters (e.g. “text/html”).

Delegates to ContentType.normalize; kept on Mime for a stable classify-API surface.

Parameters:

  • content_type (String, nil)

    raw header value

Returns:

  • (String)

    empty string when absent or blank



50
51
52
# File 'lib/webstruct/http/mime.rb', line 50

def normalize(content_type)
  ContentType.normalize(content_type)
end

.resolve(content_type, body) ⇒ Symbol

Picks a coarse parser bucket for the response body.

Parameters:

  • content_type (String, nil)

    raw Content-Type header

  • body (String)

    response body (may be binary); sniffing uses a trimmed prefix

Returns:

  • (Symbol)

    :html, :xhtml, :json, :csv, :tsv, :xml, :text, or :unknown



59
60
61
62
63
64
65
66
67
68
# File 'lib/webstruct/http/mime.rb', line 59

def resolve(content_type, body)
  base = normalize(content_type)
  type = mime_type(base)

  return sniff(body) if type.nil?

  type = sniff(body) if type == :octet_stream

  type
end

.sniff(body) ⇒ Symbol

Infers a type from the first bytes of body when the header is missing or generic.

Parameters:

  • body (String)

Returns:

  • (Symbol)


74
75
76
77
78
79
80
81
82
# File 'lib/webstruct/http/mime.rb', line 74

def sniff(body)
  string = body.to_s.lstrip

  return :json if string.start_with?("{", "[")
  return :xml if string.start_with?("<?xml")
  return :html if string.start_with?("<")

  :unknown
end