module Sprockets::HTTPUtils
def find_best_mime_type_match(q_value_header, available)
Adapted from Rack::Utils#q_values.
options.
Internal: Find the best qvalue match from an Array of available mime type
def find_best_mime_type_match(q_value_header, available) find_best_q_match(q_value_header, available) do |a, b| match_mime_type?(a, b) end end
def find_best_q_match(q_values, available, &matcher)
Adapted from Rack::Utils#q_values.
Internal: Find the best qvalue match from an Array of available options.
def find_best_q_match(q_values, available, &matcher) find_q_matches(q_values, available, &matcher).first end
def find_mime_type_matches(q_value_header, available)
Adapted from Rack::Utils#q_values.
options.
Internal: Find the all qvalue match from an Array of available mime type
def find_mime_type_matches(q_value_header, available) find_q_matches(q_value_header, available) do |a, b| match_mime_type?(a, b) end end
def find_q_matches(q_values, available, &matcher)
Adapted from Rack::Utils#q_values.
Internal: Find all qvalue matches from an Array of available options.
def find_q_matches(q_values, available, &matcher) matcher ||= lambda { |a, b| a == b } matches = [] case q_values when Array when String q_values = parse_q_values(q_values) when NilClass q_values = [] else raise TypeError, "unknown q_values type: #{q_values.class}" end q_values.each do |accepted, quality| if match = available.find { |option| matcher.call(option, accepted) } matches << [match, quality] end end matches.sort_by { |match, quality| -quality }.map { |match, quality| match } end
def match_mime_type?(value, matcher)
Returns true if the given value is a mime match for the given mime match
match_mime_type?('text/html', 'application/json') => false
match_mime_type?('text/plain', '*') => true
match_mime_type?('text/html', 'text/*') => true
Internal: Test mime type against mime range.
def match_mime_type?(value, matcher) v1, v2 = value.split('/', 2) m1, m2 = matcher.split('/', 2) (m1 == '*' || v1 == m1) && (m2.nil? || m2 == '*' || m2 == v2) end
def parse_q_values(values)
Adapted from Rack::Utils#q_values.
Internal: Parse Accept header quality values.
def parse_q_values(values) values.to_s.split(/\s*,\s*/).map do |part| value, parameters = part.split(/\s*;\s*/, 2) quality = 1.0 if md = /\Aq=([\d.]+)/.match(parameters) quality = md[1].to_f end [value, quality] end end