Class: FeduxOrgStdlib::LocaleConfigurator

Inherits:
Object
  • Object
show all
Defined in:
lib/fedux_org_stdlib/locale_configurator.rb

Overview

Configuration for language on cli

Make sure you have translations for errors:

use_empty_locale:
use_invalid_locale:

Instance Method Summary collapse

Constructor Details

#initialize(path:, default_locale: nil, enforce_available_locales: true, detector: FeduxOrgStdlib::ShellLanguageDetector.new, logger: FeduxOrgStdlib::Logging::Logger.new) ⇒ LocaleConfigurator

Returns a new instance of LocaleConfigurator.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/fedux_org_stdlib/locale_configurator.rb', line 21

def initialize(
  path:,
  default_locale: nil,
  enforce_available_locales: true,
  detector: FeduxOrgStdlib::ShellLanguageDetector.new,
  logger: FeduxOrgStdlib::Logging::Logger.new
)
  @pattern         = File.join(path, '*.yml')
  @detector        = detector
  @detected_locale = detect_locale(overwrite: default_locale)
  @logger          = logger

  I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
  I18n.load_path = locale_files
  I18n.backend.load_translations

  I18n.default_locale            = @detected_locale
  I18n.available_locales         = available_locales
  I18n.enforce_available_locales = enforce_available_locales
end

Instance Method Details

#available_localesObject



58
59
60
# File 'lib/fedux_org_stdlib/locale_configurator.rb', line 58

def available_locales
  locale_files.map { |f| File.basename(f, '.yml').to_sym }
end

#t(*args, &block) ⇒ Object



62
63
64
# File 'lib/fedux_org_stdlib/locale_configurator.rb', line 62

def t(*args, &block)
  I18n.t(*args, &block)
end

#use_locale(l) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fedux_org_stdlib/locale_configurator.rb', line 42

def use_locale(l)
  l = l.to_sym

  if l.blank?
    logger.warn I18n.t('errors.use_empty_locale', codes: available_locales.to_list, fallback_locale: detected_locale)
    return
  end

  unless valid_locale?(l)
    logger.warn I18n.t('errors.use_invalid_locale', codes: available_locales.to_list, fallback_locale: detected_locale)
    return
  end

  I18n.locale = l
end

#validate_and_return_locale(l) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/fedux_org_stdlib/locale_configurator.rb', line 66

def validate_and_return_locale(l)
  return l.to_sym if valid_locale? l

  logger.warn I18n.t('errors.use_invalid_locale', codes: available_locales.to_list, fallback_locale: detected_locale)

  detected_locale
end