Class: Middleman::Presentation::LocaleConfigurator

Inherits:
Object
  • Object
show all
Defined in:
lib/middleman-presentation-core/locale_configurator.rb

Overview

Configuration for language on cli

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.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/middleman-presentation-core/locale_configurator.rb', line 12

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



49
50
51
# File 'lib/middleman-presentation-core/locale_configurator.rb', line 49

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

#t(*args, &block) ⇒ Object



53
54
55
# File 'lib/middleman-presentation-core/locale_configurator.rb', line 53

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

#use_locale(l) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/middleman-presentation-core/locale_configurator.rb', line 33

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



57
58
59
60
61
62
63
# File 'lib/middleman-presentation-core/locale_configurator.rb', line 57

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