Class: ActionView::Base

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

Instance Method Summary collapse

Instance Method Details

#translate_with_context(key, options = {}) ⇒ Object

Redefine the translate method in ActionView (contributed by TranslationHelper) that is context-aware of what view (or partial) is being rendered. Initial scoping will be scoped to [:controller_name :view_name]



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/translator.rb', line 254

def translate_with_context(key, options={})
  # The outer scope will typically be the controller name ("blog_posts")
  # but can also be a dir of shared partials ("shared").
  outer_scope = self.template.base_path

  # The template will be the view being rendered ("show.erb" or "_ad.erb")
  inner_scope = self.template.name

  # Partials template names start with underscore, which should be removed
  inner_scope.sub!(/^_/, '')
  
  # In the case of a missing translation, fall back to letting TranslationHelper
  # put in span tag for a translation_missing.
  begin
    Translator.translate_with_scope([outer_scope, inner_scope], key, options.merge({:raise => true}))
  rescue Translator::TranslatorError, I18n::MissingTranslationData => exc
    # Call the original translate method
    str = translate_without_context(key, options)
    
    # View helper adds the translation missing span like:
    # In strict mode, do not allow TranslationHelper to add "translation missing" span like:
    # <span class="translation_missing">en, missing_string</span>
    if str =~ /span class\=\"translation_missing\"/
      # In strict mode, do not allow TranslationHelper to add "translation missing"
      raise if Translator.strict_mode?
      
      # Invoke callback if it is defined
      Translator.missing_translation_callback(exc, key, options)
    end

    str
  end
end