# encoding: utf-8 require 'fedux_org_stdlib/process_environment' require 'fedux_org_stdlib/shell_language_detector/language' module FeduxOrgStdlib # Detect language of shell # # @example Simple Usage # # detector = ShellLanguageDetector.new # lang = detector.detect # puts lang.language_code # puts lang.country_code # puts lang.encoding # # @example Overwrite detected lang # # detector = ShellLanguageDetector.new # lang = detector.detect(overwrite: [:de, :de, :utf_8] # # @example Allowed languages # # detector = ShellLanguageDetector.new # lang = detector.detect(allowed: [:de, :en]) 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.to_sym @default_country_code = default_country_code.to_sym @default_encoding = default_encoding.to_sym @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: [], overwrite: []) allowed = Array(allowed).map(&:to_sym) overwrite = Array(overwrite).map(&:to_sym) 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 unless e.nil? } language_code, country_code, encoding = *overwrite if !overwrite.blank? && overwrite.none?(&:blank?) return Language.new(language_code: language_code, country_code: country_code, encoding: encoding) if language_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