lib/accept_headers/negotiatable.rb in accept_headers-0.0.7 vs lib/accept_headers/negotiatable.rb in accept_headers-0.0.8

- old
+ new

@@ -1,14 +1,14 @@ module AcceptHeaders module Negotiatable class Error < StandardError; end class ParseError < Error; end - Q_PATTERN = /(?:\A|;)\s*(?<exists>qs*\=)\s*(?:(?<q>0\.\d{1,3}|[01])|(?:[^;]*))\s*(?:\z|;)/ - attr_reader :list + Q_PATTERN = /(?:\A|;)\s*(?<exists>qs*\=)\s*(?:(?<q>0\.\d{1,3}|[01])|(?:[^;]*))\s*(?:\z|;)/ + def initialize(header) @list = parse(header) end def negotiate(supported) @@ -20,11 +20,11 @@ supported.each do |support| if part.match(support) if part.q == 0.0 next else - return { supported: support, matched: part } + return [support, part] end end end end nil @@ -33,11 +33,33 @@ def accept?(other) negotiate(other) ? true : false end private - def parse(header) - raise NotImplementedError.new("#parse(header) is not implemented") + def no_header + raise NotImplementedError.new("#no_header is not implemented") + end + + def parse_item(entry) + raise NotImplementedError.new("#parse_item(entry) is not implemented") + end + + def parse(header, &block) + header = header.dup + header.sub!(/\A#{self.class::HEADER_PREFIX}\s*/, '') + header.strip! + return no_header if header.empty? + list = [] + header.split(',').each do |entry| + begin + item = parse_item(entry) + next if item.nil? + list << item + rescue Error + next + end + end + list.sort! { |x,y| y <=> x } end def parse_q(header) q = 1 return q unless header