1 # encoding: utf-8
2 #
3 # Memoize module simply memoizes the values returned by lookup using
4 # a flat hash and can tremendously speed up the lookup process in a backend.
5 #
6 # To enable it you can simply include the Memoize module to your backend:
7 #
8 # I18n::Backend::Simple.send(:include, I18n::Backend::Memoize)
9 #
10 # Notice that it's the responsibility of the backend to define whenever the
11 # cache should be cleaned.
12 module I18n
13 module Backend
14 module Memoize
15 def available_locales
16 @memoized_locales ||= super
17 end
18
19 def store_translations(locale, data, options = {})
20 reset_memoizations!(locale)
21 super
22 end
23
24 def reload!
25 reset_memoizations!
26 super
27 end
28
29 protected
30
31 def lookup(locale, key, scope = nil, options = {})
32 flat_key = I18n::Backend::Flatten.normalize_flat_keys(locale,
33 key, scope, options[:separator]).to_sym
34 flat_hash = memoized_lookup[locale.to_sym]
35 flat_hash.key?(flat_key) ? flat_hash[flat_key] : (flat_hash[flat_key] = super)
36 end
37
38 def memoized_lookup
39 @memoized_lookup ||= Hash.new { |h, k| h[k] = {} }
40 end
41
42 def reset_memoizations!(locale=nil)
43 @memoized_locales = nil
44 (locale ? memoized_lookup[locale.to_sym] : memoized_lookup).clear
45 end
46 end
47 end
48 en