Class: RailsI18nOnair::DatabaseBackend

Inherits:
I18n::Backend::Simple
  • Object
show all
Defined in:
lib/rails_i18n_onair/backend.rb

Overview

Database-first backend: looks up translations in the DB, falls back to whatever backend was previously configured (e.g. YAML files).

Installed automatically by the engine when the translations table exists. Usage: I18n::Backend::Chain.new(DatabaseBackend.new, existing_file_backend)

Instance Method Summary collapse

Constructor Details

#initializeDatabaseBackend

Returns a new instance of DatabaseBackend.



11
12
13
14
15
16
17
18
19
# File 'lib/rails_i18n_onair/backend.rb', line 11

def initialize
  super
  @initialized = true  # Prevent Simple from loading YAML files — we only use the DB
  @memory_cache = {}
  @loaded_locales = Set.new
  @mutex = Mutex.new

  load_translations_from_database if RailsI18nOnair.configuration.lazy_load_locales == false
end

Instance Method Details

#available_localesObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rails_i18n_onair/backend.rb', line 31

def available_locales
  cache_key = "i18n_onair:available_locales"

  if defined?(Rails) && Rails.cache && RailsI18nOnair.configuration.cache_translations
    Rails.cache.fetch(cache_key, expires_in: 5.minutes) do
      fetch_available_locales
    end
  else
    fetch_available_locales
  end
end

#init_translationsObject

Override: never load YAML files. This backend is DB-only; the Chain's second backend (file_backend) handles YAML fallback.



23
24
25
# File 'lib/rails_i18n_onair/backend.rb', line 23

def init_translations
  @initialized = true
end

#load_translations(*_filenames) ⇒ Object



27
28
29
# File 'lib/rails_i18n_onair/backend.rb', line 27

def load_translations(*_filenames)
  # no-op — YAML loading belongs to the file backend in the Chain
end

#reload!(options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rails_i18n_onair/backend.rb', line 43

def reload!(options = {})
  locale = options[:locale]

  if locale
    reload_locale(locale)
  else
    @mutex.synchronize do
      @initialized = false
      @memory_cache.clear
      @loaded_locales.clear
      @translations = {}
    end

    clear_rails_cache

    if options[:warm_up] != false && defined?(I18n)
      load_locale(I18n.default_locale)
    end
  end
end

#reload_locale(locale) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rails_i18n_onair/backend.rb', line 64

def reload_locale(locale)
  locale_sym = locale.to_sym

  @mutex.synchronize do
    @memory_cache.delete(locale_sym)
    @loaded_locales.delete(locale_sym)
    @translations.delete(locale_sym) if @translations

    if defined?(Rails) && Rails.cache
      Rails.cache.delete("i18n_onair:locale:#{locale}")
    end
  end

  load_locale(locale)
end