diff options
author | Seb Bacon <seb.bacon@gmail.com> | 2011-01-14 19:00:19 +0000 |
---|---|---|
committer | Seb Bacon <seb.bacon@gmail.com> | 2011-03-10 10:13:25 +0000 |
commit | 01dd220d34cbd84ec0d02f0533d82d9af7c8a913 (patch) | |
tree | 710d4b7a66146860ab8da9cce48abed897aa7c98 /lib | |
parent | 33f463d602f69893a1ee2587ceac337d89c2210e (diff) |
initial support for localising model data (not fully tested)
Diffstat (limited to 'lib')
-rw-r--r-- | lib/i18n_fixes.rb | 106 |
1 files changed, 106 insertions, 0 deletions
diff --git a/lib/i18n_fixes.rb b/lib/i18n_fixes.rb index 9d7a999dd..e4d679b0e 100644 --- a/lib/i18n_fixes.rb +++ b/lib/i18n_fixes.rb @@ -35,3 +35,109 @@ def gettext_interpolate(string, values) string % values.except(*reserved_keys) end end + + +module I18n + # used by Globalize plugin. + # XXX much of this stuff should (might?) be in newer versions of Rails + @@fallbacks = nil + class << self + # Returns the current fallbacks implementation. Defaults to +I18n::Locale::Fallbacks+. + def fallbacks + @@fallbacks ||= I18n::Locale::Fallbacks.new + end + end + + module Locale + module Tag + class Simple + class << self + def tag(tag) + new(tag) + end + end + + attr_reader :tag + + def initialize(*tag) + @tag = tag.join('-').to_sym + end + + def subtags + @subtags = tag.to_s.split('-').map { |subtag| subtag.to_s } + end + + def to_sym + tag + end + + def to_s + tag.to_s + end + + def to_a + subtags + end + + def parent + @parent ||= begin + segs = to_a.compact + segs.length > 1 ? self.class.tag(*segs[0..(segs.length-2)].join('-')) : nil + end + end + + def self_and_parents + @self_and_parents ||= [self] + parents + end + + def parents + @parents ||= ([parent] + (parent ? parent.parents : [])).compact + end + + + end + end + class Fallbacks < Hash + def initialize(*mappings) + @map = {} + map(mappings.pop) if mappings.last.is_a?(Hash) + self.defaults = mappings.empty? ? [I18n.default_locale.to_sym] : mappings + end + + def defaults=(defaults) + @defaults = defaults.map { |default| compute(default, false) }.flatten + end + attr_reader :defaults + + def [](locale) + raise InvalidLocale.new(locale) if locale.nil? + locale = locale.to_sym + super || store(locale, compute(locale)) + end + + def map(mappings) + mappings.each do |from, to| + from, to = from.to_sym, Array(to) + to.each do |_to| + @map[from] ||= [] + @map[from] << _to.to_sym + end + end + end + + protected + + def compute(tags, include_defaults = true) + result = Array(tags).collect do |tag| + tags = I18n::Locale::Tag::Simple.tag(tag).self_and_parents.map! { |t| t.to_sym } + tags.each { |_tag| tags += compute(@map[_tag]) if @map[_tag] } + tags + end.flatten + result.push(*defaults) if include_defaults + result.uniq.compact + end + end + autoload :Fallbacks, 'i18n/locale/fallbacks' + end +end + |