Class: I18n

Inherits:
Object
  • Object
show all
Defined in:
lib/i18n-light.rb

Overview

i18n class, the center of the program

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(strings, fallback_locale, locale = nil, warnings = false) ⇒ I18n

Initialize the i18n class

Parameters:

  • strings (Hash)

    all the strings

  • fallback_locale (Strings, Symbol)

    the locale to use if any is set

  • locale (Strings, Symbol, nil) (defaults to: nil)

    set a locale (optional)

  • warning (Boolean)

    enable warnings during runtime (default: false)



17
18
19
20
21
# File 'lib/i18n-light.rb', line 17

def initialize strings, fallback_locale, locale = nil, warnings = false
  @warnings = warnings
  @strings = strings
  @fallback_locale = fallback_locale
end

Instance Attribute Details

#localeString, Symbol

Returns the locale selection.

Returns:

  • (String, Symbol)

    the locale selection



9
10
11
# File 'lib/i18n-light.rb', line 9

def locale
  @locale
end

Instance Method Details

#t(key, subkey = nil, params = {}) ⇒ Object

Get a string in the configured locale

Parameters:

  • key (String, Symbol)

    key of the string to return

  • subkey (String, Symbol, nil) (defaults to: nil)

    subkey for categories (optional)

  • params (Hash, nil) (defaults to: {})

    params for formatting

Returns:

  • the requested key



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/i18n-light.rb', line 29

def t key, subkey = nil, params = {}
  
  # locale selection
  locale = @locale.nil? ? @fallback_locale : @locale
  t = @strings[locale]
  if t.nil?
    raise Unknownlocale, "[i18n] error : unknown locale"
  end
  
  # key selection
  t = t[key]
  if t.nil?
    puts "[i18n] warning : unknown key #{key}" if @warnings
    return
  end
  
  # subkey selection (if exists)
  t = t[subkey] unless subkey.nil?
  
  # formatting parameters
  params.each do |name, value|
    puts "[i18n] warning : unknown parameter #{name}" if @warnings && t !~ /{#{name}}/
    t.sub!("{#{name}}", value)
  end
  puts "[i18n] warning : unfilled formatting parameters" if @warnings && t =~ /{.+}/
  
  # returning the string
  t
end