Module: SplendeoTranslator

Defined in:
lib/splendeo_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: SplendeoTranslatorError

Constant Summary collapse

VERSION =

SplendeoTranslator 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
@@key_fallback_mode =

Whether to show the raw key if the locale doesn’t provide a translation

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.



147
148
149
# File 'lib/splendeo_translator.rb', line 147

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

.fallback?Boolean

If fallback mode is enabled

Returns:

  • (Boolean)


152
153
154
# File 'lib/splendeo_translator.rb', line 152

def self.fallback?
  @@fallback_mode
end

.key_fallback(enable = true) ⇒ Object

When key_fallback mode is enabled, if a key cannot be found in the set locale, it will return the key



158
159
160
# File 'lib/splendeo_translator.rb', line 158

def self.key_fallback(enable = true)
  @@key_fallback_mode = enable
end

.key_fallback?Boolean

If key_fallback mode is enabled

Returns:

  • (Boolean)


163
164
165
# File 'lib/splendeo_translator.rb', line 163

def self.key_fallback?
  @@key_fallback_mode
end

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

Invokes the missing translation callback, if it is defined



38
39
40
# File 'lib/splendeo_translator.rb', line 38

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 “]]”



213
214
215
# File 'lib/splendeo_translator.rb', line 213

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.



219
220
221
# File 'lib/splendeo_translator.rb', line 219

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 “[[”



201
202
203
# File 'lib/splendeo_translator.rb', line 201

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.



207
208
209
# File 'lib/splendeo_translator.rb', line 207

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.



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

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

.pseudo_translate?Boolean

If pseudo-translated is enabled

Returns:

  • (Boolean)


195
196
197
# File 'lib/splendeo_translator.rb', line 195

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 SplendeoTranslator)

Example:

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


53
54
55
# File 'lib/splendeo_translator.rb', line 53

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



171
172
173
174
175
176
177
178
179
180
# File 'lib/splendeo_translator.rb', line 171

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)


183
184
185
# File 'lib/splendeo_translator.rb', line 183

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.



135
136
137
# File 'lib/splendeo_translator.rb', line 135

def translate(key, options={})
  SplendeoTranslator.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.



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
124
125
126
127
128
129
# File 'lib/splendeo_translator.rb', line 76

def self.translate_with_scope(scope, key, options={})
  scope ||= [] # guard against nil scope
  
  # Let Rails 2.3 handle keys starting with "."
  raise SplendeoTranslatorError, "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
  
  # set the default value to key if key_fallback is active
  options[:default] ||= key if SplendeoTranslator.key_fallback?

  # If a string is not yet found, potentially check the default locale if in fallback mode.
  if str.nil? && SplendeoTranslator.fallback? && (I18n.locale != I18n.default_locale) && options[:locale].nil?
    # Recurse original request, but in the context of the default locale
    str ||= SplendeoTranslator.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 SplendeoTranslator.pseudo_translate? && !str.nil?
    str = SplendeoTranslator.pseudo_prepend + str + SplendeoTranslator.pseudo_append
  end
  
  str
end