Module: RGame::Engine::I18n

Defined in:
lib/rgame/engine/i18n.rb

Overview

Minimal localization: per-locale translation tables (loaded from YAML or a Hash), t(key) with %{var} interpolation and a fallback locale, and a generation counter that ticks whenever the locale changes — so cached UI text knows when to re-resolve without polling every frame. A global module (like EventDispatcher), so t is reachable anywhere. Pure Ruby; YAML is the only (stdlib) dependency.

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.generationObject (readonly)

Returns the value of attribute generation.



14
15
16
# File 'lib/rgame/engine/i18n.rb', line 14

def generation
  @generation
end

Class Method Details

.availableObject



52
# File 'lib/rgame/engine/i18n.rb', line 52

def available = @locales.keys

.defaultObject

The locale t falls back to when the current locale lacks a key.



17
# File 'lib/rgame/engine/i18n.rb', line 17

def default = @fallback

.default=(locale) ⇒ Object



19
20
21
# File 'lib/rgame/engine/i18n.rb', line 19

def default=(locale)
  @fallback = locale.to_sym
end

.load(locale, translations) ⇒ Object

Register a locale's translations (nested Hashes allowed). Keys are symbolized so YAML ("string keys") and inline symbol keys look the same to t.



32
33
34
35
# File 'lib/rgame/engine/i18n.rb', line 32

def load(locale, translations)
  @locales[locale.to_sym] = symbolize(translations)
  self
end

.load_file(locale, path) ⇒ Object



37
38
39
# File 'lib/rgame/engine/i18n.rb', line 37

def load_file(locale, path)
  load(locale, YAML.load_file(path))
end

.localeObject



41
# File 'lib/rgame/engine/i18n.rb', line 41

def locale = @current

.locale=(locale) ⇒ Object

Switching the locale bumps the generation so observers re-resolve their text.



44
45
46
47
48
49
50
# File 'lib/rgame/engine/i18n.rb', line 44

def locale=(locale)
  locale = locale.to_sym
  return if locale == @current

  @current = locale
  @generation += 1
end

.resetObject



23
24
25
26
27
28
# File 'lib/rgame/engine/i18n.rb', line 23

def reset
  @locales = {}
  @current = :en
  @fallback = :en
  @generation = 0
end

.t(key, count: nil, **vars) ⇒ Object

Resolve a dotted key ("menu.title" or :menu_title) in the current locale, then the fallback locale, then the key itself; interpolate %var from vars.

Pass count: to pluralize: the key's value is then a table of forms ({ one:, other:, optionally zero: }), and count is also exposed to interpolation as %count. English/German use the one/other rule.



60
61
62
63
64
65
66
67
# File 'lib/rgame/engine/i18n.rb', line 60

def t(key, count: nil, **vars)
  value = lookup(@current, key) || lookup(@fallback, key)
  value = pluralize(value, count) if count && value.is_a?(Hash)
  return key.to_s unless value.is_a?(String)

  vars = vars.merge(count: count) if count
  vars.empty? ? value : (value % vars)
end