1 # The Cascade module adds the ability to do cascading lookups to backends that
2 # are compatible to the Simple backend.
4 # By cascading lookups we mean that for any key that can not be found the
5 # Cascade module strips one segment off the scope part of the key and then
6 # tries to look up the key in that scope.
8 # E.g. when a lookup for the key :"foo.bar.baz" does not yield a result then
9 # the segment :bar will be stripped off the scope part :"foo.bar" and the new
10 # scope :foo will be used to look up the key :baz. If that does not succeed
11 # then the remaining scope segment :foo will be omitted, too, and again the
12 # key :baz will be looked up (now with no scope).
14 # To enable a cascading lookup one passes the :cascade option:
16 # I18n.t(:'foo.bar.baz', :cascade => true)
18 # This will return the first translation found for :"foo.bar.baz", :"foo.baz"
19 # or :baz in this order.
21 # The cascading lookup takes precedence over resolving any given defaults.
22 # I.e. defaults will kick in after the cascading lookups haven't succeeded.
24 # This behavior is useful for libraries like ActiveRecord validations where
25 # the library wants to give users a bunch of more or less fine-grained options
26 # of scopes for a particular key.
28 # Thanks to Clemens Kofler for the initial idea and implementation! See
29 # http://github.com/clemens/i18n-cascading-backend
34 def lookup(locale, key, scope = [], options = {})
35 return super unless cascade = options[:cascade]
37 cascade = { :step => 1 } unless cascade.is_a?(Hash)
38 step = cascade[:step] || 1
39 offset = cascade[:offset] || 1
40 separator = options[:separator] || I18n.default_separator
41 skip_root = cascade.has_key?(:skip_root) ? cascade[:skip_root] : true
43 scope = I18n.normalize_keys(nil, key, scope, separator)
44 key = (scope.slice!(-offset, offset) || []).join(separator)
48 return result unless result.nil?
50 end while (!scope.empty? || !skip_root) && scope.slice!(-step, step)