Class: MiniGL::Localization

Inherits:
Object
  • Object
show all
Defined in:
lib/minigl/localization.rb

Overview

This class provides methods to easily retrieve string translations from text files.

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.languageObject

The current language. It’s a symbol corresponding to the name of the file in data/text for that language, without the ‘.txt’ extension.



12
13
14
# File 'lib/minigl/localization.rb', line 12

def language
  @language
end

.languagesObject (readonly)

The list of available languages. These are symbols corresponding to the names of the files in data/text, without the ‘.txt’ extension.



8
9
10
# File 'lib/minigl/localization.rb', line 8

def languages
  @languages
end

Class Method Details

.initializeObject

Initializes the localization system. If you’re using a custom Res.prefix, call this after setting it.

The localization system will look for files with extension ‘.txt’ in the [Res.prefix]/data/text folder. In each file, each string should be specified in one line, with the following format:

identifier content content content...

Use tab characters between the identifier and the text, not white spaces. This makes it easier to make all the texts aligned and is required for the localization system to work. The identifiers will be used as symbols when retrieving strings.

The text contents support placeholders, i.e., markers that can be replaced by arguments you pass to Localization.text. To specify a placeholder, simply use the ‘$’ character. For example, if your string is:

my_string Values: $ and $

the call Localization.text(:my_string, 'test', 10) will result in “Values: test and 10.”

To include a literal ‘$’ in the text, use ‘\$’ (without the quotes). Similarly, use ‘\\’ to represent a literal backslash, and just ‘\’ to represent a line break (i.e. a “\n” in the resulting string).



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/minigl/localization.rb', line 42

def initialize
  @languages = []
  @texts = {}
  files = Dir["#{Res.prefix}text/*.txt"].sort
  files.each do |f|
    lang = f.split('/')[-1].chomp('.txt').to_sym
    @languages << lang
    @texts[lang] = {}
    File.open(f).each do |l|
      parts = l.split("\t")
      @texts[lang][parts[0].to_sym] = parts[-1].chomp
    end
  end

  @language = @languages[0]
end

.text(id, *args) ⇒ Object

Retrieves the string identified by id in the current language.

See Localization.initialize for details on how to use args.



70
71
72
73
74
75
76
# File 'lib/minigl/localization.rb', line 70

def text(id, *args)
  value = @texts[@language][id] || '<MISSING STRING>'
  args.each do |arg|
    value = value.sub(/(^|[^\\])\$/, "\\1#{arg}")
  end
  value.gsub('\\$', '$').gsub(/\\(.|$)/) { |m| m[1] == '\\' ? '\\' : "\n#{m[1]}" }
end