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).
Defined Under Namespace
Classes: InvalidLocale, MissingInterpolationArgument, MissingTranslationData
Constant Summary collapse
- LOCALE_KEY =
The
Thread.currentkey holding the thread’s locale (a Symbol); nil there means default_locale. :cybertrain_i18n_locale
Class Method Summary collapse
-
.available_locales ⇒ Array<Symbol>
The locales
I18n.locale=accepts (config.i18n_available_locales, set at boot); just the default locale until set. -
.available_locales=(list) ⇒ Array<Symbol>
-
.default_locale ⇒ Symbol
The locale every thread starts at, and the one a key falls back to (
config.i18n_default_locale, set at boot). -
.default_locale=(value) ⇒ Symbol
-
.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). -
.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:basemessage stands alone. -
.html_key?(key) ⇒ Boolean
Whether key’s text is HTML, as Rails decides it: the key ends in
_htmlor.html(or ishtml). -
.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 (I18n.humanize_attribute). -
.human_model_name(model_key) ⇒ String
A model’s name for people, as Rails’
model_name.human:activerecord.models.<model>(itsone:form when it has plural forms), else the last segment of the key humanised ("blog_comment"→"Blog comment","admin/post"→"Post"). -
.humanize_attribute(name) ⇒ String
An attribute name as words, Rails’
humanize: a trailing_idgoes,_becomes a space and the first letter is capitalized ("published_at"→"Published at","author_id"→"Author"). -
.humanize_key(segment) ⇒ String
A key segment as words, Rails’
humanize:"bar_baz"→"Bar baz". -
.install_dictionary(texts, lists) ⇒ nil
Installs the application’s dictionary.
-
.l(value, options = {}) ⇒ String
value as text in the locale’s format, as Rails’
I18n.l: a Time intime.formats.<format>, a Date indate.formats.<format>. -
.locale ⇒ Symbol
The thread’s locale: the one
I18n.locale=set on this thread, or the default locale. -
.locale=(value) ⇒ nil
Sets this thread’s locale.
-
.locale_available?(value) ⇒ Boolean
Whether value names one of I18n.available_locales, exactly (
"ja"or:ja;"JA"and"ja-JP"do not). -
.localize(value, options = {}) ⇒ String
The same as I18n.l.
-
.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?). -
.mark_missing? ⇒ Boolean
Whether a missing key answers the marked text (development and test) rather than the humanised last segment (production); see I18n.mark_missing=.
-
.missing_text(full_key) ⇒ String
"translation missing: ja.foo.bar"for the full key"ja.foo.bar". -
.plural_category(locale, count) ⇒ Symbol
The CLDR plural category of an integer count in a locale (D7), decided by the locale’s language (
pt-BRbypt): ja and zhother; fronefor 0 and 1,manyfor a non-zero multiple of 1,000,000, elseother; ruone(1, 21, 101),few(2-4, 22-24), elsemany; en and every other languageonefor 1, elseother. -
.raise_on_missing=(value) ⇒ Boolean
Whether I18n.t raises MissingTranslationData for a missing key (the
i18n_raise_on_missingsetting, set at boot). -
.t(key, options = {}) ⇒ String
The text at key (
"posts.index.title"): the current locale’s, application dictionary first, then the default locale’s. -
.translate(key, options = {}) ⇒ String
The same as I18n.t.
-
.translate_list(key, options = {}) ⇒ Array<String>
The list at key (
"date.abbr_day_names"), from the same dictionaries in the same order as I18n.t; empty when none holds it. -
.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.
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.
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>
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).
106 |
# File 'cybertrain/i18n.rb', line 106 def self.default_locale = @default_locale |
.default_locale=(value) ⇒ 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).
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.(model_key, attr, type, = {}, 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() count = [: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.
700 701 702 703 704 705 706 707 |
# File 'cybertrain/i18n.rb', line 700 def self.(model_key, attr, ) a = attr.to_s m = .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.
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).
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").
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).
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.
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.
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.
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, = {}) loc = I18n.option_locale() zone_option = [: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 = "l: expected a Time or a Date (got #{value.class.name})" raise ArgumentError, end format = [: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? = I18n.missing_text("#{loc}.#{key}") raise MissingTranslationData, end pattern = found elsif format.is_a?(String) pattern = format.to_s else = "l: format: must be a Symbol or a String (got #{format.class.name})" raise ArgumentError, 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.
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.
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).
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.
424 |
# File 'cybertrain/i18n.rb', line 424 def self.localize(value, = {}) = I18n.l(value, ) |
.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?).
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=.
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".
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.
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).
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.
250 251 252 253 254 255 |
# File 'cybertrain/i18n.rb', line 250 def self.t(key, = {}) found = I18n.find_translation(key, ) return found unless found.nil? I18n.missing_answer(I18n.option_locale(), key.to_s) end |
.translate(key, options = {}) ⇒ String
The same as t.
320 |
# File 'cybertrain/i18n.rb', line 320 def self.translate(key, = {}) = I18n.t(key, ) |
.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.
510 511 512 513 514 515 516 517 518 |
# File 'cybertrain/i18n.rb', line 510 def self.translate_list(key, = {}) k = key.to_s wanted = [: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.
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 |