This module contains several helpers to assist flattening translations. You may want to flatten translations for:
1) speed up lookups, as in the Memoize backend; 2) In case you want to store translations in a data store, as in ActiveRecord backend;
You can check both backends above for some examples. This module also keeps all links in a hash so they can be properly resolved when flattened.
normalize_keys the flatten way. This method is significantly faster and creates way less objects than the one at I18n.normalize_keys. It also handles escaping the translation keys.
# File lib/i18n/backend/flatten.rb, line 18 18: def self.normalize_flat_keys(locale, key, scope, separator) 19: keys = [scope, key].flatten.compact 20: separator ||= I18n.default_separator 21: 22: if separator != FLATTEN_SEPARATOR 23: keys.map! do |k| 24: k.to_s.tr("#{FLATTEN_SEPARATOR}#{separator}", 25: "#{SEPARATOR_ESCAPE_CHAR}#{FLATTEN_SEPARATOR}") 26: end 27: end 28: 29: keys.join(".") 30: end
Flatten keys for nested Hashes by chaining up keys:
>> { "a" => { "b" => { "c" => "d", "e" => "f" }, "g" => "h" }, "i" => "j"}.wind => { "a.b.c" => "d", "a.b.e" => "f", "a.g" => "h", "i" => "j" }
# File lib/i18n/backend/flatten.rb, line 54 54: def flatten_keys(hash, escape, prev_key=nil, &block) 55: hash.each_pair do |key, value| 56: key = escape_default_separator(key) if escape 57: curr_key = [prev_key, key].compact.join(FLATTEN_SEPARATOR).to_sym 58: yield curr_key, value 59: flatten_keys(value, escape, curr_key, &block) if value.is_a?(Hash) 60: end 61: end
Receives a hash of translations (where the key is a locale and the value is another hash) and return a hash with all translations flattened.
Nested hashes are included in the flattened hash just if subtree is true and Symbols are automatically stored as links.
# File lib/i18n/backend/flatten.rb, line 69 69: def flatten_translations(locale, data, escape, subtree) 70: hash = {} 71: flatten_keys(data, escape) do |key, value| 72: if value.is_a?(Hash) 73: hash[key] = value if subtree 74: else 75: store_link(locale, key, value) if value.is_a?(Symbol) 76: hash[key] = value 77: end 78: end 79: hash 80: end
Store flattened links.
# File lib/i18n/backend/flatten.rb, line 45 45: def links 46: @links ||= Hash.new { |h,k| h[k] = {} } 47: end
Shortcut to I18n::Backend::Flatten.normalize_flat_keys and then resolve_links.
# File lib/i18n/backend/flatten.rb, line 39 39: def normalize_flat_keys(locale, key, scope, separator) 40: key = I18n::Backend::Flatten.normalize_flat_keys(locale, key, scope, separator) 41: resolve_link(locale, key) 42: end
# File lib/i18n/backend/flatten.rb, line 88 88: def resolve_link(locale, key) 89: key, locale = key.to_s, locale.to_sym 90: links = self.links[locale] 91: 92: if links.key?(key) 93: links[key] 94: elsif link = find_link(locale, key) 95: store_link(locale, key, key.gsub(*link)) 96: else 97: key 98: end 99: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.