148 |
148 |
end
|
149 |
149 |
|
150 |
150 |
# Custom backend based on I18n::Backend::Simple with the following changes:
|
151 |
|
# * lazy loading of translation files
|
152 |
151 |
# * available_locales are determined by looking at translation file names
|
153 |
|
class Backend
|
154 |
|
(class << self; self; end).class_eval { public :include }
|
155 |
|
|
|
152 |
class Backend < ::I18n::Backend::Simple
|
156 |
153 |
module Implementation
|
157 |
|
include ::I18n::Backend::Base
|
158 |
154 |
include ::I18n::Backend::Pluralization
|
159 |
155 |
|
160 |
|
# Stores translations for the given locale in memory.
|
161 |
|
# This uses a deep merge for the translations hash, so existing
|
162 |
|
# translations will be overwritten by new ones only at the deepest
|
163 |
|
# level of the hash.
|
164 |
|
def store_translations(locale, data, options = {})
|
165 |
|
locale = locale.to_sym
|
166 |
|
translations[locale] ||= {}
|
167 |
|
data = data.deep_symbolize_keys
|
168 |
|
translations[locale].deep_merge!(data)
|
169 |
|
end
|
170 |
|
|
171 |
156 |
# Get available locales from the translations filenames
|
172 |
157 |
def available_locales
|
173 |
158 |
@available_locales ||= ::I18n.load_path.map {|path| File.basename(path, '.*')}.uniq.sort.map(&:to_sym)
|
174 |
159 |
end
|
175 |
|
|
176 |
|
# Clean up translations
|
177 |
|
def reload!
|
178 |
|
@translations = nil
|
179 |
|
@available_locales = nil
|
180 |
|
super
|
181 |
|
end
|
182 |
|
|
183 |
|
protected
|
184 |
|
|
185 |
|
def init_translations(locale)
|
186 |
|
locale = locale.to_s
|
187 |
|
paths = ::I18n.load_path.select {|path| File.basename(path, '.*') == locale}
|
188 |
|
load_translations(paths)
|
189 |
|
translations[locale] ||= {}
|
190 |
|
end
|
191 |
|
|
192 |
|
def translations
|
193 |
|
@translations ||= {}
|
194 |
|
end
|
195 |
|
|
196 |
|
# Looks up a translation from the translations hash. Returns nil if
|
197 |
|
# eiher key is nil, or locale, scope or key do not exist as a key in the
|
198 |
|
# nested translations hash. Splits keys or scopes containing dots
|
199 |
|
# into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
|
200 |
|
# <tt>%w(currency format)</tt>.
|
201 |
|
def lookup(locale, key, scope = [], options = {})
|
202 |
|
init_translations(locale) unless translations.key?(locale)
|
203 |
|
keys = ::I18n.normalize_keys(locale, key, scope, options[:separator])
|
204 |
|
|
205 |
|
keys.inject(translations) do |result, _key|
|
206 |
|
_key = _key.to_sym
|
207 |
|
return nil unless result.is_a?(Hash) && result.has_key?(_key)
|
208 |
|
result = result[_key]
|
209 |
|
result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
|
210 |
|
result
|
211 |
|
end
|
212 |
|
end
|
213 |
160 |
end
|
214 |
161 |
|
215 |
|
include Implementation
|
216 |
162 |
# Adds fallback to default locale for untranslated strings
|
217 |
163 |
include ::I18n::Backend::Fallbacks
|
218 |
164 |
end
|