Sha256: 84fedc6d0b9285f08bab0ccfe2ee877a86c1fabd13abcc6818fe9f2fc5514e08

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

# encoding: utf-8
require 'fedux_org_stdlib/process_environment'
require 'fedux_org_stdlib/shell_language_detector/language'

module FeduxOrgStdlib
  class ShellLanguageDetector
    private

    attr_reader :environment, :default_encoding, :default_language_code, :default_country_code

    public

    def initialize(default_language_code: :en, default_country_code: :gb, default_encoding: :utf_8, environment: ProcessEnvironment.new)
      @default_language_code = default_language_code
      @default_country_code  = default_country_code
      @default_encoding      = default_encoding
      @environment           = environment
    end

    # @param [Array, Symbol, String]  allowed
    #   The languages which are allowed
    #
    # @return [Language]
    #    The detected language or the default language if no allowed language was detected
    def detect(allowed: [])
      lang = environment.fetch 'LANG'
      language_code, country_code, encoding = lang.scan(/([^_-]+)[_-]([^.]+)\.([A-Za-z0-9_-]*)/i).flatten.map(&:downcase).map { |e| e.gsub('-', '_') }.map { |e| e.to_sym if !e.nil? }
      allowed = Array(allowed).map(&:to_sym)

      return Language.new(language_code: language_code, country_code: country_code, encoding: encoding) if language_code && country_code && (allowed.blank? || allowed.include?(language_code))
      Language.new(language_code: default_language_code, country_code: default_country_code, encoding: default_encoding)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fedux_org-stdlib-0.6.30 lib/fedux_org_stdlib/shell_language_detector.rb