Module: Rack::Acceptable::Media

Defined in:
lib/rack/acceptable/mixin/media.rb

Instance Method Summary collapse

Instance Method Details

#accept_media?(thing) ⇒ Boolean

Checks if the MIME-Type passed acceptable.

Returns:

  • (Boolean)


40
41
42
43
44
# File 'lib/rack/acceptable/mixin/media.rb', line 40

def accept_media?(thing)
  MIMETypes.weigh_mime_type(thing, acceptable_media).first > 0
rescue
  false
end

#acceptable_mediaObject

Returns

An Array with completely parsed MIME-Types (incl. qvalues and accept-extensions; see Rack::Acceptable::MIMETypes). Default qvalue is 1.0.

Raises

ArgumentError

Syntax of the The Accept request-header is bad. For example, one of Media-Ranges is not in a RFC ‘Media-Range’ pattern (type or subtype is invalid, or there’s something like “*/foo”) or, at last, one of MIME-Types has malformed qvalue.



34
35
36
37
# File 'lib/rack/acceptable/mixin/media.rb', line 34

def acceptable_media
  header = env[Const::ENV_HTTP_ACCEPT].to_s
  header.split(Utils::COMMA_SPLITTER).map! { |entry| MIMETypes.parse_mime_type(entry) }
end

#acceptable_media_rangesObject

Returns

An Array with Media-Ranges (as Strings) / wildcards and associated qvalues. Default qvalue is 1.0.

Raises

ArgumentError

There’s a malformed qvalue in header.



15
16
17
18
19
20
# File 'lib/rack/acceptable/mixin/media.rb', line 15

def acceptable_media_ranges
  Utils.extract_qvalues(env[Const::ENV_HTTP_ACCEPT].to_s)
rescue
  raise ArgumentError,
  "Malformed Accept header: #{env[Const::ENV_HTTP_ACCEPT].inspect}"
end

#best_media_for(thing) ⇒ Object

Returns the best match for the MIME-Type or pattern (like “text/*” etc) passed or nil.



48
49
50
51
52
53
54
55
# File 'lib/rack/acceptable/mixin/media.rb', line 48

def best_media_for(thing)
  weight = MIMETypes.weigh_mime_type(thing, acceptable_media)
  if weight.first > 0
    acceptable_media.at(-weight.last)
  else
    nil
  end
end

#negotiate_media(*things) ⇒ Object Also known as: preferred_media_from



57
58
59
60
# File 'lib/rack/acceptable/mixin/media.rb', line 57

def negotiate_media(*things)
  flag = (things.last == true || things.last == false) ? things.pop : false
  MIMETypes.detect_best_mime_type(things, acceptable_media, flag)
end