lib/accept_headers/encoding/negotiator.rb in accept_headers-0.0.7 vs lib/accept_headers/encoding/negotiator.rb in accept_headers-0.0.8

- old
+ new

@@ -4,24 +4,35 @@ module AcceptHeaders class Encoding class Negotiator include Negotiatable + ENCODING_PATTERN = /^\s*(?<encoding>[\w!#$%^&*\-\+{}\\|'.`~]+)\s*$/ + HEADER_PREFIX = 'Accept-Encoding:' + + def negotiate(supported) + support, match = super(supported) + return nil if support.nil? && match.nil? + begin + return parse(support).first + rescue Encoding::Error + return nil + end + end + private - def parse(original_header) - header = original_header.dup - header.sub!(/\AAccept-Encoding:\s*/, '') + def no_header + [Encoding.new] + end + + def parse_item(header) + return nil if header.nil? header.strip! - return [Encoding.new] if header.empty? - encodings = [] - header.split(',').each do |entry| - encoding_arr = entry.split(';', 2) - next if encoding_arr[0].nil? - encoding = Encoding::ENCODING_PATTERN.match(encoding_arr[0]) - next if encoding.nil? - encodings << Encoding.new(encoding[:encoding], q: parse_q(encoding_arr[1])) - end - encodings.sort! { |x,y| y <=> x } + encoding_string, q_string = header.split(';', 2) + raise Error if encoding_string.nil? + encoding = ENCODING_PATTERN.match(encoding_string) + raise Error if encoding.nil? + Encoding.new(encoding[:encoding], q: parse_q(q_string)) end end end end