Module: Translator

Defined in:
lib/translator.rb

Overview

Extentions to make internationalization (i18n) of a Rails application simpler. Support the method translate (or shorter t) in models/view/controllers/mailers.

Defined Under Namespace

Modules: Assertions, I18nExtensions Classes: TranslatorError

Constant Summary collapse

VERSION =

Translator version

'1.0.0'
@@strict_mode =

Whether strict mode is enabled

false
@@fallback_mode =

Whether to fallback from the set locale to the default locale

false
@@pseudo_translate =

Whether to pseudo-translate all fetched strings

false
@@pseudo_prepend =

Pseudo-translation text to prend to fetched strings. Used as a visible marker. Default is “[”

"["
@@pseudo_append =

Pseudo-translation text to append to fetched strings. Used as a visible marker. Default is “]”

"]"
@@missing_translation_callback =

An optional callback to be notified when there are missing translations in views

nil

Class Method Summary collapse

Class Method Details

.fallback(enable = true) ⇒ Object

When fallback mode is enabled if a key cannot be found in the set locale, it uses the default locale. So, for example, if an app is mostly localized to Spanish (:es), but a new page is added then Spanish users will continue to see mostly Spanish content but the English version (assuming the default_locale is :en) for the new page that has not yet been translated to Spanish.



141
142
143
# File 'lib/translator.rb', line 141

def self.fallback(enable = true)
  @@fallback_mode = enable
end

.fallback?Boolean

If fallback mode is enabled

Returns:

  • (Boolean)


146
147
148
# File 'lib/translator.rb', line 146

def self.fallback?
  @@fallback_mode
end

.missing_translation_callback(exception, key, options = {}) ⇒ Object

Invokes the missing translation callback, if it is defined



35
36
37
# File 'lib/translator.rb', line 35

def self.missing_translation_callback(exception, key, options = {}) #:nodoc:
  @@missing_translation_callback.call(exception, key, options) if !@@missing_translation_callback.nil?
end

.pseudo_appendObject

Pseudo-translation text to append to fetched strings. Used as a visible marker. Default is “]]”



196
197
198
# File 'lib/translator.rb', line 196

def self.pseudo_append
  @@pseudo_append
end

.pseudo_append=(v) ⇒ Object

Set the pseudo-translation text to append to fetched strings. Used as a visible marker.



202
203
204
# File 'lib/translator.rb', line 202

def self.pseudo_append=(v)
  @@pseudo_append = v
end

.pseudo_prependObject

Pseudo-translation text to prepend to fetched strings. Used as a visible marker. Default is “[[”



184
185
186
# File 'lib/translator.rb', line 184

def self.pseudo_prepend
  @@pseudo_prepend
end

.pseudo_prepend=(v) ⇒ Object

Set the pseudo-translation text to prepend to fetched strings. Used as a visible marker.



190
191
192
# File 'lib/translator.rb', line 190

def self.pseudo_prepend=(v)
  @@pseudo_prepend = v
end

.pseudo_translate(enable = true) ⇒ Object

Toggle a pseudo-translation mode that will prepend / append special text to all fetched strings. This is useful during testing to view pages and visually confirm that strings have been fully extracted into locale bundles.



173
174
175
# File 'lib/translator.rb', line 173

def self.pseudo_translate(enable = true)
  @@pseudo_translate = enable
end

.pseudo_translate?Boolean

If pseudo-translated is enabled

Returns:

  • (Boolean)


178
179
180
# File 'lib/translator.rb', line 178

def self.pseudo_translate?
  @@pseudo_translate
end

.set_missing_translation_callback(&block) ⇒ Object

Set an optional block that gets called when there’s a missing translation within a view. This can be used to log missing translations in production.

Block takes two required parameters:

  • exception (original I18n::MissingTranslationData that was raised for the failed translation)

  • key (key that was missing)

  • options (hash of options sent to translator)

Example:

set_missing_translation_callback do |ex, key, options|
  logger.info("Failed to find #{key}")
end


50
51
52
# File 'lib/translator.rb', line 50

def self.set_missing_translation_callback(&block)
  @@missing_translation_callback = block
end

.strict_mode(enable_strict = true) ⇒ Object

Toggle whether to true an exception on all MissingTranslationData exceptions Useful during testing to ensure all keys are found. Passing true enables strict mode, false installs the default exception handler which does not raise on MissingTranslationData



154
155
156
157
158
159
160
161
162
163
# File 'lib/translator.rb', line 154

def self.strict_mode(enable_strict = true)
  @@strict_mode = enable_strict
  
  if enable_strict
    # Switch to using contributed exception handler
    I18n.exception_handler = :strict_i18n_exception_handler
  else
    I18n.exception_handler = :default_exception_handler
  end
end

.strict_mode?Boolean

Get if it is in strict mode

Returns:

  • (Boolean)


166
167
168
# File 'lib/translator.rb', line 166

def self.strict_mode?
  @@strict_mode
end

.translate(key, options = {}) ⇒ Object Also known as: t

Generic translate method that mimics I18n.translate (e.g. no automatic scoping) but includes locale fallback and strict mode behavior.



129
130
131
# File 'lib/translator.rb', line 129

def translate(key, options={})
  Translator.translate_with_scope([], key, options)
end

.translate_with_scope(scope, key, options = {}) ⇒ Object

Performs lookup with a given scope. The scope should be an array of strings or symbols ordered from highest to lowest scoping. For example, for a given PicturesController with an action “show” the scope should be [‘pictures’, ‘show’] which happens automatically.

The key and options parameters follow the same rules as the I18n library (they are passed through).

The search order is from most specific scope to most general (and then using a default value, if provided). So continuing the previous example, if the key was “title” and options included :default => ‘Some Picture’ then it would continue searching until it found a value for:

  • pictures.show.title

  • pictures.title

  • title

  • use the default value (if provided)

The key itself can contain a scope. For example, if there were a set of shared error messages within the Pictures controller, that could be found using a key like “errors.deleted_picture”. The inital search with narrowest scope (‘pictures.show.errors.deleted_picture’) will not find a value, but the subsequent search with broader scope (‘pictures.errors.deleted_picture’) will find the string.

Raises:



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/translator.rb', line 73

def self.translate_with_scope(scope, key, options={})
  scope ||= [] # guard against nil scope
  
  # Let Rails 2.3 handle keys starting with "."
  raise TranslatorError, "Skip keys with leading dot" if key.to_s.first == "."
  
  # Keep the original options clean
  original_scope = scope.dup
  scoped_options = {}.merge(options)
      
  # Raise to know if the key was found
  scoped_options[:raise] = true
  
  # Remove any default value when searching with scope
  scoped_options.delete(:default)
  
  str = nil # the string being looked for
  
  # Loop through each scope until a string is found.
  # Example: starts with scope of [:blog_posts :show] then tries scope [:blog_posts] then 
  # without any automatically added scope ("[]").
  while str.nil?
    # Set scope to use for search
    scoped_options[:scope] = scope
  
    begin
      # try to find key within scope (dup the options because I18n modifies the hash)
      str = I18n.translate(key, scoped_options.dup)
    rescue I18n::MissingTranslationData => exc
      # did not find the string, remove a layer of scoping.
      # break when there are no more layers to remove (pop returns nil)
      break if scope.pop.nil?
    end
  end

  # If a string is not yet found, potentially check the default locale if in fallback mode.
  if str.nil? && Translator.fallback? && (I18n.locale != I18n.default_locale) && options[:locale].nil?
    # Recurse original request, but in the context of the default locale
    str ||= Translator.translate_with_scope(original_scope, key, options.merge({:locale => I18n.default_locale}))
  end
  
  # If a string was still not found, fall back to trying original request (gets default behavior)
  str ||= I18n.translate(key, options)
  
  # If pseudo-translating, prepend / append marker text
  if Translator.pseudo_translate? && !str.nil?
    str = Translator.pseudo_prepend + str + Translator.pseudo_append
  end
  
  str
end