Sha256: 2e7b2852d0906bbbe3040e4aa0b0ba2756c4e4efe81b3b4a8b270e1edee92177

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

require 'http_headers/utils'
require 'delegate'

module HttpHeaders
  class AcceptLanguage < DelegateClass(Array)
    VERSION = '0.2.0'

    def initialize(value)
      __setobj__ HttpHeaders::Utils::List.new(value, entry_klazz: Entry)
    end

    class Entry

      DELIMITER = '-'

      attr_reader :locale, :region, :language

      def initialize(locale, index:, parameters:)
        self.locale = locale
        # TODO: support extlang correctly, maybe we don't even need this
        self.language, self.region = locale.split(DELIMITER)
        self.parameters = parameters
        self.index = index

        freeze
      end

      # noinspection RubyInstanceMethodNamingConvention
      def q
        parameters.fetch(:q) { 1.0 }.to_f
      end

      def <=>(other)
        quality = other.q <=> q
        return quality unless quality.zero?
        index <=> other.index
      end

      def [](parameter)
        parameters.fetch(String(parameter).to_sym)
      end

      def to_header
        to_s
      end

      def to_s
        [locale].concat(parameters.map { |k, v| "#{k}=#{v}" }).compact.reject(&:empty?).join('; ')
      end

      private

      attr_writer :locale, :region, :language
      attr_accessor :parameters, :index
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
http_headers-accept_language-0.2.0 lib/http_headers/accept_language.rb