]> git.openstreetmap.org Git - rails.git/blob - vendor/plugins/globalize2/lib/globalize/backend/static.rb
Add Globalize2 so that we get some nice fall backs to other languages when a translat...
[rails.git] / vendor / plugins / globalize2 / lib / globalize / backend / static.rb
1 require 'globalize/backend/pluralizing'
2 require 'globalize/locale/fallbacks'
3 require 'globalize/translation'
4
5 module Globalize
6   module Backend
7     class Static < Pluralizing
8       def initialize(*args)
9         add(*args) unless args.empty?
10       end
11
12       def translate(locale, key, options = {})
13         result, default, fallback = nil, options.delete(:default), nil
14         I18n.fallbacks[locale].each do |fallback|
15           begin
16             result = super(fallback, key, options) and break
17           rescue I18n::MissingTranslationData
18           end
19         end
20         result ||= default locale, default, options
21
22         attrs = {:requested_locale => locale, :locale => fallback, :key => key, :options => options}
23         translation(result, attrs) || raise(I18n::MissingTranslationData.new(locale, key, options))
24       end
25
26       protected
27
28         alias :orig_interpolate :interpolate unless method_defined? :orig_interpolate
29         def interpolate(locale, string, values = {})
30           result = orig_interpolate(locale, string, values)
31           translation = translation(string)
32           translation.nil? ? result : translation.replace(result)
33         end
34
35         def translation(result, meta = nil)
36           return unless result
37
38           case result
39           when Numeric
40             result
41           when String
42             result = Translation::Static.new(result) unless result.is_a? Translation::Static
43             result.set_meta meta
44             result
45           when Hash
46             Hash[*result.map do |key, value|
47               [key, translation(value, meta)]
48             end.flatten]
49           when Array
50             result.map do |value|
51               translation(value, meta)
52             end
53           else
54             result
55             # raise "unexpected translation type: #{result.inspect}"
56           end
57         end
58     end
59   end
60 end