Sha256: ab2959df692a2d6746c5dbdb913f66ae0d7d4cbf8fe2c7f78bbc675836d404bf

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

module Browser
  class AcceptLanguage
    def self.languages
      @languages ||= YAML.load_file(Browser.root.join("languages.yml"))
    end

    def self.parse(accept_language)
      return [] unless accept_language

      accept_language
        .split(",")
        .map {|string| string.squeeze(" ").strip }
        .map {|part| new(part) }
        .reject {|al| al.quality.zero? }
        .sort_by.with_index {|al, idx| [-al.quality, idx] }
    end

    attr_reader :part

    def initialize(part)
      @part = part
    end

    def full
      @full ||= [code, region].compact.join("-")
    end

    def name
      self.class.languages[full] || self.class.languages[code]
    end

    def code
      @code ||= begin
        code = part[/\A([^-;]+)/, 1]
        code&.downcase
      end
    end

    def region
      @region ||= begin
        region = part[/\A(?:.*?)-([^;-]+)/, 1]
        region&.upcase
      end
    end

    def quality
      @quality ||= begin
        Float(quality_value || 1.0)
      rescue ArgumentError
        0.1
      end
    end

    private def quality_value
      qvalue = part[/;q=([\d.]+)/, 1]
      qvalue = "0.0" if /\A0\.0?\z/.match?(qvalue)
      qvalue = qvalue.squeeze(".") if qvalue
      qvalue
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
browser-6.1.0 lib/browser/accept_language.rb
browser-6.0.0 lib/browser/accept_language.rb