Module: I18n

Defined in:
cybertrain/i18n.rb

Overview

I18n, a top-level module as in Rails (plan decision D1), so application code writes I18n.t and I18n.locale as there.

Two dictionaries answer: the application’s (config/locales/**/*.yml, compiled by spin run gen into gen/locales.rb, which installs it with I18n.install_dictionary when it loads) and the framework’s bundled one (cybertrain/locales/en.yml and ja.yml, rails-i18n’s keys, compiled into cybertrain/locales/bundled.rb). A key is looked up in the current locale, the application’s dictionary first, then in the default locale the same way (D2): an application’s key overrides the bundled one.

The current locale belongs to the thread (Thread.current, under LOCALE_KEY), so connections served at the same time keep their own; every controller action starts at the default locale (D5-D7, R4).

Examples:

# config/locales/ja.yml:  ja: { greeting: "こんにちは、%{name}" }
I18n.locale = :ja
I18n.t("greeting", name: "Ann")             # => "こんにちは、Ann"
I18n.t("errors.messages.blank")             # => "を入力してください" (bundled)
I18n.with_locale(:en) { I18n.t("errors.messages.blank") }  # => "can't be blank"

Defined Under Namespace

Classes: InvalidLocale, MissingInterpolationArgument, MissingTranslationData

Constant Summary collapse

LOCALE_KEY =

The Thread.current key holding the thread’s locale (a Symbol); nil there means default_locale.

:cybertrain_i18n_locale

Class Method Summary collapse

Class Method Details

.available_locales ⇒ Array<Symbol>

The locales I18n.locale= accepts (config.i18n_available_locales, set at boot); just the default locale until set.

Returns:

  • (Array<Symbol>)


119
120
121
122
123
124
# File 'cybertrain/i18n.rb', line 119

def self.available_locales
  list = @available_locales
  return [@default_locale] if list.empty?

  list
end

.available_locales=(list) ⇒ Array<Symbol>

Parameters:

  • list (Array<Symbol>) —

    empty means the default locale alone

Returns:

  • (Array<Symbol>)


129
130
131
# File 'cybertrain/i18n.rb', line 129

def self.available_locales=(list)
  @available_locales = list
end

.default_locale ⇒ Symbol

The locale every thread starts at, and the one a key falls back to (config.i18n_default_locale, set at boot).

Returns:

  • (Symbol)


106
# File 'cybertrain/i18n.rb', line 106

def self.default_locale = @default_locale

.default_locale=(value) ⇒ Symbol

Parameters:

  • value (Symbol)

Returns:

  • (Symbol)


111
112
113
# File 'cybertrain/i18n.rb', line 111

def self.default_locale=(value)
  @default_locale = value
end

.error_message(model_key, attr, type, options = {}, value = nil) ⇒ String

A validation message, looked up when the validator runs, along Rails’ chain (plan decision D10): activerecord.errors.models.<model>.attributes.<attr>.<type>, activerecord.errors.models.<model>.<type>, activerecord.errors.messages.<type>, errors.attributes.<attr>.<type>, errors.messages.<type>; the whole chain in the current locale, then in the default one (as Rails’ fallbacks run the defaults per locale). %{attribute} and %{model} are the human names, %{count} the count: (an Integer, which also picks the plural form) or count_text: (a String, numericality’s limit: no plural form), %{value} the attribute’s value as text when value is given (validators give it).

Examples:

I18n.error_message("post", :title, :too_short, { count: 8 })
# => "is too short (minimum is 8 characters)"
I18n.error_message("post", :rating, :greater_than, { count_text: "1.5" })
# => "must be greater than 1.5"

Parameters:

  • model_key (String) —

    "" skips the two model keys

  • attr (Symbol, String)
  • type (Symbol, String) —

    Rails’ key: :blank, :too_short, …

  • options (Hash{Symbol => Object}) (defaults to: {}) —

    count:, count_text:, other interpolation values

  • value (String, nil) (defaults to: nil) —

    the attribute’s value as text, for %{value}

Returns:

  • (String)

Raises:

  • (MissingTranslationData) —

    for a type no dictionary holds, when asked to (the text names the most specific key)



663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
# File 'cybertrain/i18n.rb', line 663

def self.error_message(model_key, attr, type, options = {}, value = nil)
  mk = model_key.to_s
  a = attr.to_s
  ty = type.to_s
  keys = Array.new(0) { "" }
  unless mk.empty?
    keys << "activerecord.errors.models.#{mk}.attributes.#{a}.#{ty}"
    keys << "activerecord.errors.models.#{mk}.#{ty}"
  end
  keys << "activerecord.errors.messages.#{ty}"
  keys << "errors.attributes.#{a}.#{ty}"
  keys << "errors.messages.#{ty}"
  vars = I18n.interpolation_vars(options)
  count = options[:count]
  counted = count.is_a?(Integer)
  n = counted ? count.to_i : 0
  loc = I18n.locale
  found = I18n.first_in_locale(loc, keys, counted, n)
  default = I18n.default_locale
  found = I18n.first_in_locale(default, keys, counted, n) if found.nil? && default != loc
  return I18n.missing_answer(loc, keys[0]) if found.nil?

  # The human names cost a lookup each: made only for a text that uses them.
  vars["attribute"] = I18n.human_attribute_name(mk, a) if found.include?("%{attribute}") && !vars.key?("attribute")
  vars["model"] = I18n.human_model_name(mk) if found.include?("%{model}") && !vars.key?("model")
  vars["value"] = value.to_s if !value.nil? && !vars.key?("value")
  I18n.interpolate_vars(found, vars)
end

.full_message(model_key, attr, message) ⇒ String

One message of errors.full_messages: errors.format ("%{attribute} %{message}", ja "%{attribute}%{message}") with the attribute’s human name; a :base message stands alone.

Parameters:

  • model_key (String)
  • attr (Symbol, String)
  • message (String)

Returns:

  • (String)


700
701
702
703
704
705
706
707
# File 'cybertrain/i18n.rb', line 700

def self.full_message(model_key, attr, message)
  a = attr.to_s
  m = message.to_s
  return m if a == "base"

  attribute = I18n.human_attribute_name(model_key, a)
  I18n.t("errors.format", { default: "%{attribute} %{message}", attribute: attribute, message: m })
end

.html_key?(key) ⇒ Boolean

Whether key’s text is HTML, as Rails decides it: the key ends in _html or .html (or is html). The template t and Controller#t escape the values interpolated into such a text.

Parameters:

  • key (String)

Returns:

  • (Boolean)


328
329
330
331
# File 'cybertrain/i18n.rb', line 328

def self.html_key?(key)
  k = key.to_s
  k == "html" || k.end_with?("_html") || k.end_with?(".html")
end

.human_attribute_name(model_key, attr) ⇒ String

An attribute’s name for people, as Rails’ human_attribute_name: activerecord.attributes.<model>.<attr>, else the humanised attribute (humanize_attribute). A generated model answers it as Post.human_attribute_name(:title).

Examples:

# ja.yml: ja: { activerecord: { attributes: { post: { title: "タイトル" } } } }
I18n.with_locale(:ja) { I18n.human_attribute_name("post", :title) }  # => "タイトル"
I18n.human_attribute_name("post", :author_id)                       # => "Author"

Parameters:

  • model_key (String) —

    the model’s key, Inflector.underscore of its class name ("post", "admin/post"); "" skips the dictionary

  • attr (Symbol, String)

Returns:

  • (String)


610
611
612
613
614
615
616
617
618
# File 'cybertrain/i18n.rb', line 610

def self.human_attribute_name(model_key, attr)
  a = attr.to_s
  mk = model_key.to_s
  unless mk.empty?
    found = I18n.find_translation("activerecord.attributes.#{mk}.#{a}")
    return found unless found.nil?
  end
  I18n.humanize_attribute(a)
end

.human_model_name(model_key) ⇒ String

A model’s name for people, as Rails’ model_name.human: activerecord.models.<model> (its one: form when it has plural forms), else the last segment of the key humanised ("blog_comment" → "Blog comment", "admin/post" → "Post").

Parameters:

  • model_key (String)

Returns:

  • (String)


627
628
629
630
631
632
633
634
635
# File 'cybertrain/i18n.rb', line 627

def self.human_model_name(model_key)
  mk = model_key.to_s
  found = I18n.find_translation("activerecord.models.#{mk}", { count: 1 })
  return found unless found.nil?

  slash = mk.rindex("/")
  element = slash.nil? ? mk : mk[(slash + 1)..].to_s
  I18n.humanize_attribute(element)
end

.humanize_attribute(name) ⇒ String

An attribute name as words, Rails’ humanize: a trailing _id goes, _ becomes a space and the first letter is capitalized ("published_at" → "Published at", "author_id" → "Author"). Intermediate results are bound to locals, never chained: in threaded programs an unnamed temporary can be collected while the next call in the chain still reads it (see Inflector.underscore).

Parameters:

  • name (String)

Returns:

  • (String)


590
591
592
593
594
595
# File 'cybertrain/i18n.rb', line 590

def self.humanize_attribute(name)
  s = name.to_s
  base = s.end_with?("_id") && s.length > 3 ? s[0, s.length - 3].to_s : s
  spaced = base.tr("_", " ")
  spaced.capitalize
end

.humanize_key(segment) ⇒ String

A key segment as words, Rails’ humanize: "bar_baz" → "Bar baz". What a missing key shows in production.

Parameters:

  • segment (String)

Returns:

  • (String)


575
576
577
578
579
# File 'cybertrain/i18n.rb', line 575

def self.humanize_key(segment)
  s = segment.to_s
  spaced = s.tr("_", " ")
  spaced.capitalize
end

.install_dictionary(texts, lists) ⇒ nil

Installs the application’s dictionary. gen/locales.rb’s last line calls it with Gen::Locales.resolver and Gen::Locales.list_resolver; the bundled dictionary needs no installing (I18n reads Cybertrain::BundledLocales directly). Called once, at load, before any request.

Parameters:

  • texts (Proc) —

    answers the String at a full key ("ja.posts.index.title"), or nil when there is none

  • lists (Proc) —

    answers the Array at a full key, empty when there is none

Returns:

  • (nil)


96
97
98
99
100
# File 'cybertrain/i18n.rb', line 96

def self.install_dictionary(texts, lists)
  @app_texts = texts
  @app_lists = lists
  nil
end

.l(value, options = {}) ⇒ String

value as text in the locale’s format, as Rails’ I18n.l: a Time in time.formats.<format>, a Date in date.formats.<format>. format: is a Symbol naming the format (:default when not given, :short, :long, or any other the dictionaries hold) or a strftime pattern String; locale: formats in another locale. %a %A %b %B take the dictionary’s date.abbr_day_names, date.day_names, date.abbr_month_names and date.month_names, %p and %P its time.am / time.pm (upper- and lower-cased, as the i18n gem does; “” for a Date), %^a and the like upper-case the name; every other directive is strftime’s.

A Time is rendered in Time.zone (spec section 4): its wall fields, %z and %Z are the zone’s, and so are the day and month names and %p. zone: (an IANA name) renders this one call in another zone. A Time that carries an offset of its own (getlocal("+09:00")) keeps it unless zone: is given. A Date is rendered as it is.

Examples:

I18n.l(Time.utc(2026, 11, 10, 9, 5), format: :long)    # => "November 10, 2026 09:05"
I18n.l(Time.utc(2026, 11, 11, 20), format: "%H:%M %Z", zone: "Asia/Tokyo")  # => "05:00 JST"
I18n.l(Date.new(2026, 11, 10), locale: :ja)            # => "2026/11/10"
I18n.l(Time.utc(2026, 11, 10, 9, 5), format: "%a %p", locale: :ja)  # => "火 午前"

Parameters:

  • value (Time, Date)
  • options (Hash{Symbol => Object}) (defaults to: {})

Returns:

  • (String)

Raises:

  • (ArgumentError) —

    "l: expected a Time or a Date (got Integer)", unknown time zone "Mars/Base" for a zone: the system zoneinfo does not have, or a pattern directive the strftime walk does not know

  • (MissingTranslationData) —

    "translation missing: en.time.formats.nope" for a format Symbol no dictionary holds

  • (InvalidLocale) —

    for a locale: that is not available



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'cybertrain/i18n.rb', line 371

def self.l(value, options = {})
  loc = I18n.option_locale(options)
  zone_option = options[:zone]
  zone = zone_option.nil? ? Cybertrain::Clock.zone : Cybertrain::ZonedTime.zone_from(zone_option)
  subject = value
  kind = ""
  wday = 0
  mon = 0
  hour = -1
  case value
  when Time
    kind = "time"
    # zone: renders this call in that zone whatever offset the Time has.
    instant = zone_option.nil? ? value : value.getutc
    subject = instant
    shown = Cybertrain::Strftime.zoned_time(instant, zone)
    wday = shown.wday
    mon = shown.mon
    hour = shown.hour
  when Date
    kind = "date"
    wday = value.wday
    mon = value.mon
  else
    message = "l: expected a Time or a Date (got #{value.class.name})"
    raise ArgumentError, message
  end
  format = options[:format]
  pattern = ""
  if format.nil? || format.is_a?(Symbol)
    name = format.nil? ? "default" : format.to_s
    key = "#{kind}.formats.#{name}"
    found = I18n.find_in_locales(loc, key, false, 0)
    if found.nil?
      message = I18n.missing_text("#{loc}.#{key}")
      raise MissingTranslationData, message
    end
    pattern = found
  elsif format.is_a?(String)
    pattern = format.to_s
  else
    message = "l: format: must be a Symbol or a String (got #{format.class.name})"
    raise ArgumentError, message
  end
  named = I18n.localized_names(pattern, loc, wday, mon, hour)
  Cybertrain::Strftime.walk(subject, named, "l format", zone)
end

.locale ⇒ Symbol

The thread’s locale: the one I18n.locale= set on this thread, or the default locale. A controller action starts at the default locale.

Returns:

  • (Symbol)


156
157
158
159
# File 'cybertrain/i18n.rb', line 156

def self.locale
  value = Thread.current[LOCALE_KEY]
  value.nil? ? I18n.default_locale : value
end

.locale=(value) ⇒ nil

Sets this thread’s locale. The value is compared with the names of available_locales and never turned into a Symbol itself, so a request parameter can be passed as is; nil goes back to the default locale.

Examples:

I18n.locale = params[:locale] if I18n.locale_available?(params[:locale])

Parameters:

  • value (Symbol, String, nil)

Returns:

  • (nil)

Raises:



171
172
173
174
175
176
177
178
# File 'cybertrain/i18n.rb', line 171

def self.locale=(value)
  if value.nil?
    Thread.current[LOCALE_KEY] = nil
  else
    Thread.current[LOCALE_KEY] = I18n.resolve_locale(value)
  end
  nil
end

.locale_available?(value) ⇒ Boolean

Whether value names one of available_locales, exactly ("ja" or :ja; "JA" and "ja-JP" do not).

Parameters:

  • value (Symbol, String, nil)

Returns:

  • (Boolean)


185
186
187
188
189
190
191
# File 'cybertrain/i18n.rb', line 185

def self.locale_available?(value)
  return false if value.nil?

  name = value.to_s
  I18n.available_locales.each { |l| return true if l.to_s == name }
  false
end

.localize(value, options = {}) ⇒ String

The same as l.

Parameters:

  • value (Time, Date)
  • options (Hash{Symbol => Object}) (defaults to: {})

Returns:

  • (String)


424
# File 'cybertrain/i18n.rb', line 424

def self.localize(value, options = {}) = I18n.l(value, options)

.mark_missing=(value) ⇒ Boolean

Whether a missing key answers "translation missing: ja.foo.bar" (development and test, the default) or the humanised last segment, "Bar" (production; boot sets it to !production?).

Parameters:

  • value (Boolean)

Returns:

  • (Boolean)


148
149
150
# File 'cybertrain/i18n.rb', line 148

def self.mark_missing=(value)
  @mark_missing = value
end

.mark_missing? ⇒ Boolean

Whether a missing key answers the marked text (development and test) rather than the humanised last segment (production); see mark_missing=.

Returns:

  • (Boolean)


338
# File 'cybertrain/i18n.rb', line 338

def self.mark_missing? = @mark_missing

.missing_text(full_key) ⇒ String

"translation missing: ja.foo.bar" for the full key "ja.foo.bar".

Parameters:

  • full_key (String)

Returns:

  • (String)


723
# File 'cybertrain/i18n.rb', line 723

def self.missing_text(full_key) = "translation missing: #{full_key}"

.plural_category(locale, count) ⇒ Symbol

The CLDR plural category of an integer count in a locale (D7), decided by the locale’s language (pt-BR by pt): ja and zh other; fr one for 0 and 1, many for a non-zero multiple of 1,000,000, else other; ru one (1, 21, 101), few (2-4, 22-24), else many; en and every other language one for 1, else other.

Examples:

I18n.plural_category(:ru, 22)   # => :few

Parameters:

Returns:

  • (Symbol)


531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'cybertrain/i18n.rb', line 531

def self.plural_category(locale, count)
  s = locale.to_s
  lang = I18n.base_language(s)
  n = count.abs
  case lang
  when "ja", "zh"
    :other
  when "fr"
    return :one if n < 2
    return :many if n % 1_000_000 == 0

    :other
  when "ru"
    d = n % 10
    h = n % 100
    return :one if d == 1 && h != 11
    return :few if d >= 2 && d <= 4 && (h < 12 || h > 14)

    :many
  else
    n == 1 ? :one : :other
  end
end

.raise_on_missing=(value) ⇒ Boolean

Whether t raises MissingTranslationData for a missing key (the i18n_raise_on_missing setting, set at boot).

Parameters:

  • value (Boolean)

Returns:

  • (Boolean)


138
139
140
# File 'cybertrain/i18n.rb', line 138

def self.raise_on_missing=(value)
  @raise_on_missing = value
end

.t(key, options = {}) ⇒ String

The text at key ("posts.index.title"): the current locale’s, application dictionary first, then the default locale’s.

Options: default: (a String, or a Symbol naming another key) answers when no dictionary holds the key; count: (an Integer) picks the plural form under the key (zero for 0 when present, then the locale’s category, then other; see plural_category) and fills %{count}; count_text: (a String) fills %{count} without picking a form; locale: looks up in another locale. Every other option fills the %{name} of its name; %% is a literal %, so %%{x} gives %{x}.

A missing key answers "translation missing: ja.foo.bar", or "Bar" after I18n.mark_missing = false, or raises after I18n.raise_on_missing = true.

Examples:

I18n.t("greeting", name: "Ann")                  # "Hello, %{name}" => "Hello, Ann"
I18n.t("errors.template.header", count: 2, model: "post")
# => "2 errors prohibited this post from being saved"
I18n.t("nope", default: "Nothing")              # => "Nothing"

Parameters:

  • key (String, Symbol)
  • options (Hash{Symbol => Object}) (defaults to: {})

Returns:

  • (String)

Raises:



250
251
252
253
254
255
# File 'cybertrain/i18n.rb', line 250

def self.t(key, options = {})
  found = I18n.find_translation(key, options)
  return found unless found.nil?

  I18n.missing_answer(I18n.option_locale(options), key.to_s)
end

.translate(key, options = {}) ⇒ String

The same as t.

Parameters:

  • key (String, Symbol)
  • options (Hash{Symbol => Object}) (defaults to: {})

Returns:

  • (String)


320
# File 'cybertrain/i18n.rb', line 320

def self.translate(key, options = {}) = I18n.t(key, options)

.translate_list(key, options = {}) ⇒ Array<String>

The list at key ("date.abbr_day_names"), from the same dictionaries in the same order as t; empty when none holds it. locale: is the one option.

Examples:

I18n.translate_list("date.abbr_day_names")   # => ["Sun", "Mon", ...]

Parameters:

  • key (String, Symbol)
  • options (Hash{Symbol => Object}) (defaults to: {})

Returns:

  • (Array<String>)


510
511
512
513
514
515
516
517
518
# File 'cybertrain/i18n.rb', line 510

def self.translate_list(key, options = {})
  k = key.to_s
  wanted = options[:locale]
  loc = wanted.nil? ? I18n.locale : I18n.resolve_locale(wanted)
  found = I18n.list_in_locale(loc, k)
  return found unless found.empty?

  I18n.list_in_locale(I18n.default_locale, k)
end

.with_locale(value) ⇒ String

Runs the block with this thread’s locale set to value, then puts the previous one back, also when the block raises.

Examples:

I18n.with_locale(:ja) { I18n.t("posts.index.title") }   # => "投稿"

Parameters:

  • value (Symbol, String)

Returns:

  • (String) —

    the block’s value

Raises:



211
212
213
214
215
216
217
218
219
220
# File 'cybertrain/i18n.rb', line 211

def self.with_locale(value)
  saved = Thread.current[LOCALE_KEY]
  I18n.locale = value
  begin
    result = yield
  ensure
    Thread.current[LOCALE_KEY] = saved
  end
  result
end