Sha256: d70bba6e1478a2bc1534e64b76d3e110d87e06dfc730d572329104cf435e65fe

Contents?: true

Size: 1.14 KB

Versions: 4

Compression:

Stored size: 1.14 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(&:quality)
        .reverse
    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 if code
      end
    end

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

    def quality
      @quality ||= Float(quality_value || 1.0)
    end

    private

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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
browser-2.5.2 lib/browser/accept_language.rb
browser-2.5.1 lib/browser/accept_language.rb
browser-2.5.0 lib/browser/accept_language.rb
browser-2.4.0 lib/browser/accept_language.rb