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