]> git.openstreetmap.org Git - rails.git/blob - vendor/plugins/globalize2/lib/globalize/locale/fallbacks.rb
c4acd57a8b42362ab5fc31c1131c091c7e2542e4
[rails.git] / vendor / plugins / globalize2 / lib / globalize / locale / fallbacks.rb
1 require 'globalize/locale/language_tag'
2
3 module I18n
4   @@fallbacks = nil
5     
6   class << self
7     # Returns the current fallbacks. Defaults to +Globalize::Locale::Fallbacks+.
8     def fallbacks
9       @@fallbacks ||= Globalize::Locale::Fallbacks.new
10     end
11     
12     # Sets the current fallbacks. Used to set a custom fallbacks instance.
13     def fallbacks=(fallbacks) 
14       @@fallbacks = fallbacks
15     end
16   end
17 end
18
19 module Globalize
20   module Locale
21     class Fallbacks < Hash
22       def initialize(*defaults)
23         @map = {}
24         map defaults.pop if defaults.last.is_a?(Hash)
25         
26         defaults = [I18n.default_locale.to_sym] if defaults.empty?
27         self.defaults = defaults 
28       end
29       
30       def defaults=(defaults)
31         @defaults = defaults.map{|default| compute(default, false) }.flatten << :root
32       end
33       attr_reader :defaults
34       
35       def [](tag)
36         tag = tag.to_sym
37         has_key?(tag) ? fetch(tag) : store(tag, compute(tag))
38       end
39     
40       def map(mappings)
41         mappings.each do |from, to|
42           from, to = from.to_sym, Array(to)
43           to.each do |to|
44             @map[from] ||= []
45             @map[from] << to.to_sym
46           end
47         end
48       end
49       
50       protected
51     
52       def compute(tags, include_defaults = true)
53         result = Array(tags).collect do |tag|
54           tags = LanguageTag::tag(tag.to_sym).parents(true).map! {|t| t.to_sym }
55           tags.each{|tag| tags += compute(@map[tag]) if @map[tag] }
56           tags
57         end.flatten
58         result.push *defaults if include_defaults
59         result.uniq
60       end
61     end
62   end
63 end