Class: Moirai::KeyFinder
- Inherits:
-
Object
- Object
- Moirai::KeyFinder
- Includes:
- I18n::Backend::Base
- Defined in:
- app/models/moirai/key_finder.rb
Constant Summary collapse
- MUTEX =
Mutex to ensure that concurrent translations loading will be thread-safe
Mutex.new
Instance Method Summary collapse
-
#file_paths_for(key, locale: I18n.locale) ⇒ Object
TODO: remove locale default Returns all the file_paths where the key is found, including gems.
-
#initialize ⇒ KeyFinder
constructor
A new instance of KeyFinder.
- #load_file(filename) ⇒ Object
- #moirai_translations(do_init: false) ⇒ Object
- #store_moirai_translations(filename, locale, data, options) ⇒ Object
Constructor Details
#initialize ⇒ KeyFinder
Returns a new instance of KeyFinder.
10 11 12 |
# File 'app/models/moirai/key_finder.rb', line 10 def initialize load_translations end |
Instance Method Details
#file_paths_for(key, locale: I18n.locale) ⇒ Object
TODO: remove locale default Returns all the file_paths where the key is found, including gems.
16 17 18 19 20 21 22 23 |
# File 'app/models/moirai/key_finder.rb', line 16 def file_paths_for(key, locale: I18n.locale) return [] if key.blank? locale ||= I18n.locale moirai_translations[locale.to_sym].select do |_filename, data| data.dig(*key.split(".")).present? end.map { |k, _| k }.sort { |file_path| file_path.start_with?(Rails.root.to_s) ? 0 : 1 } end |
#load_file(filename) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'app/models/moirai/key_finder.rb', line 41 def load_file(filename) type = File.extname(filename).tr(".", "").downcase raise I18n::UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true) data, keys_symbolized = send(:"load_#{type}", filename) unless data.is_a?(Hash) raise I18n::InvalidLocaleData.new(filename, "expects it to return a hash, but does not") end data.each do |locale, d| store_moirai_translations(filename, locale, d || {}, skip_symbolize_keys: keys_symbolized) end data end |
#moirai_translations(do_init: false) ⇒ Object
33 34 35 36 37 38 39 |
# File 'app/models/moirai/key_finder.rb', line 33 def moirai_translations(do_init: false) @moirai_translations ||= Concurrent::Hash.new do |h, k| MUTEX.synchronize do h[k] = Concurrent::Hash.new end end end |
#store_moirai_translations(filename, locale, data, options) ⇒ Object
25 26 27 28 29 30 31 |
# File 'app/models/moirai/key_finder.rb', line 25 def store_moirai_translations(filename, locale, data, ) moirai_translations[locale] ||= Concurrent::Hash.new locale = locale.to_sym moirai_translations[locale] ||= Concurrent::Hash.new moirai_translations[locale][filename] = data.with_indifferent_access end |