1 require 'i18n/backend/base'
2 require 'active_support/json'
3 require 'active_support/ordered_hash' # active_support/json/encoding uses ActiveSupport::OrderedHash but does not require it
7 # This is a basic backend for key value stores. It receives on
8 # initialization the store, which should respond to three methods:
10 # * store#[](key) - Used to get a value
11 # * store#[]=(key, value) - Used to set a value
12 # * store#keys - Used to get all keys
14 # Since these stores only supports string, all values are converted
15 # to JSON before being stored, allowing it to also store booleans,
16 # hashes and arrays. However, this store does not support Procs.
18 # As the ActiveRecord backend, Symbols are just supported when loading
19 # translations from the filesystem or through explicit store translations.
21 # Also, avoid calling I18n.available_locales since it's a somehow
22 # expensive operation in most stores.
26 # To setup I18n to use TokyoCabinet in memory is quite straightforward:
28 # require 'rufus/tokyo/cabinet' # gem install rufus-tokyo
29 # I18n.backend = I18n::Backend::KeyValue.new(Rufus::Tokyo::Cabinet.new('*'))
33 # You may make this backend even faster by including the Memoize module.
34 # However, notice that you should properly clear the cache if you change
35 # values directly in the key-store.
39 # In most backends, you are allowed to retrieve part of a translation tree:
41 # I18n.backend.store_translations :en, :foo => { :bar => :baz }
42 # I18n.t "foo" #=> { :bar => :baz }
44 # This backend supports this feature by default, but it slows down the storage
45 # of new data considerably and makes hard to delete entries. That said, you are
46 # allowed to disable the storage of subtrees on initialization:
48 # I18n::Backend::KeyValue.new(@store, false)
50 # This is useful if you are using a KeyValue backend chained to a Simple backend.
57 def initialize(store, subtrees=true)
58 @store, @subtrees = store, subtrees
61 def store_translations(locale, data, options = {})
62 escape = options.fetch(:escape, true)
63 flatten_translations(locale, data, escape, @subtrees).each do |key, value|
64 key = "#{locale}.#{key}"
68 if @subtrees && (old_value = @store[key])
69 old_value = ActiveSupport::JSON.decode(old_value)
70 value = old_value.deep_symbolize_keys.deep_merge!(value) if old_value.is_a?(Hash)
73 raise "Key-value stores cannot handle procs"
76 @store[key] = ActiveSupport::JSON.encode([value]) unless value.is_a?(Symbol)
81 locales = @store.keys.map { |k| k =~ /\./; $` }
84 locales.map! { |k| k.to_sym }
90 def lookup(locale, key, scope = [], options = {})
91 key = normalize_flat_keys(locale, key, scope, options[:separator])
92 value = @store["#{locale}.#{key}"]
93 value = ActiveSupport::JSON.decode(value)[0] if value
94 value.is_a?(Hash) ? value.deep_symbolize_keys : value
98 include Implementation