moduleSprockets# Internal: HTTP URI utilities. Many adapted from Rack::Utils. Mixed into# Environment.moduleHTTPUtilsextendself# Public: Test mime type against mime range.## match_mime_type?('text/html', 'text/*') => true# match_mime_type?('text/plain', '*') => true# match_mime_type?('text/html', 'application/json') => false## Returns true if the given value is a mime match for the given mime match# specification, false otherwise.defmatch_mime_type?(value,matcher)v1,v2=value.split('/',2)m1,m2=matcher.split('/',2)(m1=='*'||v1==m1)&&(m2.nil?||m2=='*'||m2==v2)end# Public: Return values from Hash where the key matches the mime type.## hash - Hash of String matcher keys to Object values# mime_type - String mime type## Returns Array of Object values.defmatch_mime_type_keys(hash,mime_type)type,subtype=mime_type.split('/',2)[hash["*"],hash["*/*"],hash["#{type}/*"],hash["#{type}/#{subtype}"]].compactend# Internal: Parse Accept header quality values.## Adapted from Rack::Utils#q_values.## Returns an Array of [String, Float].defparse_q_values(values)values.to_s.split(/\s*,\s*/).mapdo|part|value,parameters=part.split(/\s*;\s*/,2)quality=1.0ifmd=/\Aq=([\d.]+)/.match(parameters)quality=md[1].to_fend[value,quality]endend# Internal: Find all qvalue matches from an Array of available options.## Adapted from Rack::Utils#q_values.## Returns Array of matched Strings from available Array or [].deffind_q_matches(q_values,available,&matcher)matcher||=lambda{|a,b|a==b}matches=[]caseq_valueswhenArraywhenStringq_values=parse_q_values(q_values)whenNilClassq_values=[]elseraiseTypeError,"unknown q_values type: #{q_values.class}"endq_values.eachdo|accepted,quality|ifmatch=available.find{|option|matcher.call(option,accepted)}matches<<[match,quality]endendmatches.sort_by{|match,quality|-quality}.map{|match,quality|match}end# Internal: Find the best qvalue match from an Array of available options.## Adapted from Rack::Utils#q_values.## Returns the matched String from available Array or nil.deffind_best_q_match(q_values,available,&matcher)find_q_matches(q_values,available,&matcher).firstend# Internal: Find the all qvalue match from an Array of available mime type# options.## Adapted from Rack::Utils#q_values.## Returns Array of matched mime type Strings from available Array or [].deffind_mime_type_matches(q_value_header,available)find_q_matches(q_value_header,available)do|a,b|match_mime_type?(a,b)endend# Internal: Find the best qvalue match from an Array of available mime type# options.## Adapted from Rack::Utils#q_values.## Returns the matched mime type String from available Array or nil.deffind_best_mime_type_match(q_value_header,available)find_best_q_match(q_value_header,available)do|a,b|match_mime_type?(a,b)endendendend