Module: Tina4::Localization

Defined in:
lib/tina4/localization.rb

Constant Summary collapse

LOCALE_DIRS =
%w[locales translations i18n src/locales].freeze

Class Method Summary collapse

Class Method Details

.add(locale, key, value) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/tina4/localization.rb', line 67

def add(locale, key, value)
  translations[locale.to_s] ||= {}
  keys = key.to_s.split(".")
  hash = translations[locale.to_s]
  keys[0..-2].each do |k|
    hash[k] ||= {}
    hash = hash[k]
  end
  hash[keys.last] = value
end

.available_localesObject



78
79
80
# File 'lib/tina4/localization.rb', line 78

def available_locales
  translations.keys
end

.current_localeObject



13
14
15
# File 'lib/tina4/localization.rb', line 13

def current_locale
  @current_locale || ENV["TINA4_LOCALE"] || "en"
end

.current_locale=(locale) ⇒ Object



17
18
19
# File 'lib/tina4/localization.rb', line 17

def current_locale=(locale)
  @current_locale = locale.to_s
end

.load(root_dir = Dir.pwd) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/tina4/localization.rb', line 21

def load(root_dir = Dir.pwd)
  LOCALE_DIRS.each do |dir|
    locale_dir = File.join(root_dir, dir)
    next unless Dir.exist?(locale_dir)

    Dir.glob(File.join(locale_dir, "*.json")).each do |file|
      locale = File.basename(file, ".json")
      data = JSON.parse(File.read(file))
      translations[locale] ||= {}
      translations[locale].merge!(data)
      Tina4::Log.debug("Loaded locale: #{locale} from #{file}")
    end

    # Also support YAML
    Dir.glob(File.join(locale_dir, "*.{yml,yaml}")).each do |file|
      begin
        require "yaml"
        locale = File.basename(file, File.extname(file))
        data = YAML.safe_load(File.read(file))
        translations[locale] ||= {}
        translations[locale].merge!(data) if data.is_a?(Hash)
      rescue LoadError
        Tina4::Log.warning("YAML support requires the 'yaml' gem")
      end
    end
  end
end

.t(key, locale: nil, default: nil, **interpolations) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/tina4/localization.rb', line 49

def t(key, locale: nil, default: nil, **interpolations)
  lang = locale || current_locale
  value = lookup(lang, key)

  if value.nil? && lang != "en"
    value = lookup("en", key)
  end

  value = default || key if value.nil?

  # Interpolation: "Hello %{name}" => "Hello World"
  interpolations.each do |k, v|
    value = value.gsub("%{#{k}}", v.to_s)
  end

  value
end

.translationsObject



9
10
11
# File 'lib/tina4/localization.rb', line 9

def translations
  @translations ||= {}
end