i18n 0.2.1 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of i18n might be problematic. Click here for more details.

Files changed (77) hide show
  1. data/README.textile +44 -9
  2. data/Rakefile +2 -1
  3. data/VERSION +1 -1
  4. data/lib/i18n.rb +60 -15
  5. data/lib/i18n/backend.rb +14 -0
  6. data/lib/i18n/backend/active_record.rb +69 -0
  7. data/lib/i18n/backend/active_record/store_procs.rb +37 -0
  8. data/lib/i18n/backend/active_record/translation.rb +82 -0
  9. data/lib/i18n/backend/active_record_missing.rb +55 -0
  10. data/lib/i18n/backend/base.rb +235 -0
  11. data/lib/i18n/backend/cache.rb +71 -0
  12. data/lib/i18n/backend/chain.rb +74 -0
  13. data/lib/i18n/backend/fallbacks.rb +51 -0
  14. data/lib/i18n/backend/gettext.rb +75 -0
  15. data/lib/i18n/backend/helpers.rb +53 -0
  16. data/lib/i18n/backend/metadata.rb +73 -0
  17. data/lib/i18n/backend/pluralization.rb +57 -0
  18. data/lib/i18n/backend/simple.rb +15 -227
  19. data/lib/i18n/core_ext/object/meta_class.rb +5 -0
  20. data/lib/i18n/{string.rb → core_ext/string/interpolate.rb} +2 -0
  21. data/lib/i18n/exceptions.rb +2 -0
  22. data/lib/i18n/gettext.rb +25 -0
  23. data/lib/i18n/helpers.rb +5 -0
  24. data/lib/i18n/helpers/gettext.rb +64 -0
  25. data/lib/i18n/locale.rb +6 -0
  26. data/lib/i18n/locale/fallbacks.rb +98 -0
  27. data/lib/i18n/locale/tag.rb +28 -0
  28. data/lib/i18n/locale/tag/parents.rb +24 -0
  29. data/lib/i18n/locale/tag/rfc4646.rb +76 -0
  30. data/lib/i18n/locale/tag/simple.rb +41 -0
  31. data/test/all.rb +7 -2
  32. data/test/api/basics.rb +3 -1
  33. data/test/api/interpolation.rb +35 -4
  34. data/test/api/lambda.rb +5 -3
  35. data/test/api/link.rb +4 -2
  36. data/test/api/localization/date.rb +2 -0
  37. data/test/api/localization/date_time.rb +3 -1
  38. data/test/api/localization/lambda.rb +4 -2
  39. data/test/api/localization/time.rb +3 -1
  40. data/test/api/pluralization.rb +12 -15
  41. data/test/api/translation.rb +5 -3
  42. data/test/backend/active_record/active_record_test.rb +40 -0
  43. data/test/backend/active_record/all.rb +3 -0
  44. data/test/backend/active_record/api_test.rb +54 -0
  45. data/test/backend/active_record/setup.rb +166 -0
  46. data/test/backend/active_record_missing/active_record_missing_test.rb +63 -0
  47. data/test/backend/all/api_test.rb +88 -0
  48. data/test/backend/cache/cache_test.rb +69 -0
  49. data/test/backend/chain/api_test.rb +80 -0
  50. data/test/backend/chain/chain_test.rb +64 -0
  51. data/test/backend/fallbacks/api_test.rb +84 -0
  52. data/test/backend/fallbacks/fallbacks_test.rb +57 -0
  53. data/test/backend/metadata/metadata_test.rb +65 -0
  54. data/test/backend/pluralization/api_test.rb +86 -0
  55. data/test/backend/pluralization/pluralization_test.rb +43 -0
  56. data/test/backend/simple/all.rb +2 -0
  57. data/test/backend/simple/api_test.rb +27 -20
  58. data/test/backend/simple/helpers_test.rb +26 -0
  59. data/test/backend/simple/lookup_test.rb +2 -1
  60. data/test/backend/simple/{setup/localization.rb → setup.rb} +29 -11
  61. data/test/backend/simple/translations_test.rb +1 -6
  62. data/test/{string_test.rb → core_ext/string/interpolate_test.rb} +4 -2
  63. data/test/fixtures/locales/de.po +67 -0
  64. data/test/fixtures/locales/en.rb +2 -0
  65. data/test/fixtures/locales/plurals.rb +113 -0
  66. data/test/gettext/api_test.rb +204 -0
  67. data/test/gettext/backend_test.rb +84 -0
  68. data/test/i18n_exceptions_test.rb +3 -1
  69. data/test/i18n_load_path_test.rb +8 -1
  70. data/test/i18n_test.rb +30 -7
  71. data/test/locale/fallbacks_test.rb +128 -0
  72. data/test/locale/tag/rfc4646_test.rb +145 -0
  73. data/test/locale/tag/simple_test.rb +35 -0
  74. data/test/test_helper.rb +11 -5
  75. data/test/with_options.rb +2 -0
  76. metadata +75 -11
  77. data/test/backend/simple/setup/base.rb +0 -21
@@ -0,0 +1,53 @@
1
+ module I18n
2
+ module Backend
3
+ module Helpers
4
+ # Return a new hash with all keys and nested keys converted to symbols.
5
+ def deep_symbolize_keys(hash)
6
+ hash.inject({}) { |result, (key, value)|
7
+ value = deep_symbolize_keys(value) if value.is_a?(Hash)
8
+ result[(key.to_sym rescue key) || key] = value
9
+ result
10
+ }
11
+ end
12
+
13
+ # Flatten keys for nested Hashes by chaining up keys using the separator
14
+ # >> { "a" => { "b" => { "c" => "d", "e" => "f" }, "g" => "h" }, "i" => "j"}.wind
15
+ # => { "a.b.c" => "d", "a.b.e" => "f", "a.g" => "h", "i" => "j" }
16
+ def wind_keys(hash, separator = ".", prev_key = nil, result = {})
17
+ hash.inject(result) do |result, pair|
18
+ key, value = *pair
19
+ curr_key = [prev_key, key].compact.join(separator)
20
+ if value.is_a?(Hash)
21
+ wind_keys(value, separator, curr_key, result)
22
+ else
23
+ result[curr_key] = value
24
+ end
25
+ result
26
+ end
27
+ end
28
+
29
+ # Expand keys chained by the the given separator through nested Hashes
30
+ # >> { "a.b.c" => "d", "a.b.e" => "f", "a.g" => "h", "i" => "j" }.unwind
31
+ # => { "a" => { "b" => { "c" => "d", "e" => "f" }, "g" => "h" }, "i" => "j"}
32
+ def unwind_keys(hash, separator = ".")
33
+ result = {}
34
+ hash.each do |key, value|
35
+ keys = key.split(separator)
36
+ curr = result
37
+ curr = curr[keys.shift] ||= {} while keys.size > 1
38
+ curr[keys.shift] = value
39
+ end
40
+ result
41
+ end
42
+
43
+ # # Flatten the given array once
44
+ # def flatten_once(array)
45
+ # result = []
46
+ # for element in array # a little faster than each
47
+ # result.push(*element)
48
+ # end
49
+ # result
50
+ # end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,73 @@
1
+ # I18n translation metadata is useful when you want to access information
2
+ # about how a translation was looked up, pluralized or interpolated in
3
+ # your application.
4
+ #
5
+ # msg = I18n.t(:message, :default => 'Hi!', :scope => :foo)
6
+ # msg.translation_metadata
7
+ # # => { :key => :message, :scope => :foo, :default => 'Hi!' }
8
+ #
9
+ # If a :count option was passed to #translate it will be set to the metadata.
10
+ # Likewise, if any interpolation variables were passed they will also be set.
11
+ #
12
+ # To enable translation metadata you can simply include the Metadata module
13
+ # into the Simple backend class - or whatever other backend you are using:
14
+ #
15
+ # I18n::Backend::Simple.send(:include, I18n::Backend::Metadata)
16
+
17
+ require 'i18n/core_ext/object/meta_class'
18
+
19
+ module I18n
20
+ module Backend
21
+ module Metadata
22
+ class << self
23
+ def included(base)
24
+ Object.class_eval do
25
+ def translation_metadata
26
+ @translation_metadata ||= {}
27
+ end
28
+
29
+ def translation_metadata=(translation_metadata)
30
+ @translation_metadata = translation_metadata
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ def translate(locale, key, options = {})
37
+ metadata = {
38
+ :locale => locale,
39
+ :key => key,
40
+ :scope => options[:scope],
41
+ :default => options[:default],
42
+ :separator => options[:separator],
43
+ :values => options.reject { |name, value| Base::RESERVED_KEYS.include?(name) }
44
+ }
45
+ with_metadata(metadata) { super }
46
+ end
47
+
48
+ def interpolate(locale, string, values = {})
49
+ with_metadata(:original => string) do
50
+ preserve_translation_metadata(string) { super }
51
+ end if string
52
+ end
53
+
54
+ def pluralize(locale, entry, count)
55
+ with_metadata(:count => count) { super }
56
+ end
57
+
58
+ protected
59
+
60
+ def with_metadata(metadata, &block)
61
+ result = yield
62
+ result.translation_metadata = result.translation_metadata.merge(metadata) if result
63
+ result
64
+ end
65
+
66
+ def preserve_translation_metadata(object, &block)
67
+ result = yield
68
+ result.translation_metadata = object.translation_metadata if result
69
+ result
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,57 @@
1
+ # encoding: utf-8
2
+
3
+ # I18n locale fallbacks are useful when you want your application to use
4
+ # translations from other locales when translations for the current locale are
5
+ # missing. E.g. you might want to use :en translations when translations in
6
+ # your applications main locale :de are missing.
7
+ #
8
+ # To enable locale specific pluralizations you can simply include the
9
+ # Pluralization module to the Simple backend - or whatever other backend you
10
+ # are using.
11
+ #
12
+ # I18n::Backend::Simple.send(:include, I18n::Backend::Pluralization)
13
+ #
14
+ # You also need to make sure to provide pluralization algorithms to the
15
+ # backend, i.e. include them to your I18n.load_path accordingly.
16
+ module I18n
17
+ module Backend
18
+ module Pluralization
19
+ # Overwrites the Base backend translate method so that it will check the
20
+ # translation meta data space (:i18n) for a locale specific pluralization
21
+ # rule and use it to pluralize the given entry. I.e. the library expects
22
+ # pluralization rules to be stored at I18n.t(:'i18n.plural.rule')
23
+ #
24
+ # Pluralization rules are expected to respond to #call(entry, count) and
25
+ # return a pluralization key. Valid keys depend on the translation data
26
+ # hash (entry) but it is generally recommended to follow CLDR's style,
27
+ # i.e., return one of the keys :zero, :one, :few, :many, :other.
28
+ #
29
+ # The :zero key is always picked directly when count equals 0 AND the
30
+ # translation data has the key :zero. This way translators are free to
31
+ # either pick a special :zero translation even for languages where the
32
+ # pluralizer does not return a :zero key.
33
+ def pluralize(locale, entry, count)
34
+ return entry unless entry.is_a?(Hash) and count
35
+
36
+ pluralizer = pluralizer(locale)
37
+ if pluralizer.respond_to?(:call)
38
+ key = count == 0 && entry.has_key?(:zero) ? :zero : pluralizer.call(count)
39
+ raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
40
+ entry[key]
41
+ else
42
+ super
43
+ end
44
+ end
45
+
46
+ protected
47
+
48
+ def pluralizers
49
+ @pluralizers ||= {}
50
+ end
51
+
52
+ def pluralizer(locale)
53
+ pluralizers[locale] ||= lookup(locale, :'i18n.plural.rule')
54
+ end
55
+ end
56
+ end
57
+ end
@@ -1,234 +1,22 @@
1
- require 'yaml'
1
+ # encoding: utf-8
2
+
3
+ # Stub class for the Simple backend. The actual implementation is provided by
4
+ # the backend Base class. This makes it easier to extend the Simple backend's
5
+ # behaviour by including modules. E.g.:
6
+ #
7
+ # module I18n::Backend::Pluralization
8
+ # def pluralize(*args)
9
+ # # extended pluralization logic
10
+ # super
11
+ # end
12
+ # end
13
+ #
14
+ # I18n::Backend::Simple.send(:include, I18n::Backend::Pluralization)
2
15
 
3
16
  module I18n
4
17
  module Backend
5
18
  class Simple
6
- RESERVED_KEYS = [:scope, :default, :separator]
7
- INTERPOLATION_SYNTAX_PATTERN = /(\\\\)?\{\{([^\}]+)\}\}/
8
-
9
- # Accepts a list of paths to translation files. Loads translations from
10
- # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
11
- # for details.
12
- def load_translations(*filenames)
13
- filenames.each { |filename| load_file(filename) }
14
- end
15
-
16
- # Stores translations for the given locale in memory.
17
- # This uses a deep merge for the translations hash, so existing
18
- # translations will be overwritten by new ones only at the deepest
19
- # level of the hash.
20
- def store_translations(locale, data)
21
- merge_translations(locale, data)
22
- end
23
-
24
- def translate(locale, key, options = {})
25
- raise InvalidLocale.new(locale) if locale.nil?
26
- return key.map { |k| translate(locale, k, options) } if key.is_a?(Array)
27
-
28
- count, scope, default, separator = options.values_at(:count, *RESERVED_KEYS)
29
- values = options.reject { |name, value| RESERVED_KEYS.include?(name) }
30
-
31
- entry = lookup(locale, key, scope, separator)
32
- entry = entry.nil? ? default(locale, key, default, options) : resolve(locale, key, entry, options)
33
-
34
- raise(I18n::MissingTranslationData.new(locale, key, options)) if entry.nil?
35
- entry = pluralize(locale, entry, count)
36
- entry = interpolate(locale, entry, values)
37
- entry
38
- end
39
-
40
- # Acts the same as +strftime+, but returns a localized version of the
41
- # formatted date string. Takes a key from the date/time formats
42
- # translations as a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
43
- def localize(locale, object, format = :default, options={})
44
- raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
45
-
46
- if Symbol === format
47
- type = object.respond_to?(:sec) ? 'time' : 'date'
48
- format = lookup(locale, :"#{type}.formats.#{format}")
49
- end
50
-
51
- format = resolve(locale, object, format, options.merge(:raise => true))
52
- format = format.dup if format
53
-
54
- # TODO check which format strings are present, then bulk translate them, then replace them
55
- format.gsub!(/%a/, translate(locale, :"date.abbr_day_names", :format => format)[object.wday]) if format.include?('%a')
56
- format.gsub!(/%A/, translate(locale, :"date.day_names", :format => format)[object.wday]) if format.include?('%A')
57
- format.gsub!(/%b/, translate(locale, :"date.abbr_month_names", :format => format)[object.mon]) if format.include?('%b')
58
- format.gsub!(/%B/, translate(locale, :"date.month_names", :format => format)[object.mon]) if format.include?('%B')
59
- format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}", :format => format)) if format.include?('%p') && object.respond_to?(:hour)
60
-
61
- object.strftime(format)
62
- end
63
-
64
- def initialized?
65
- @initialized ||= false
66
- end
67
-
68
- # Returns an array of locales for which translations are available
69
- def available_locales
70
- init_translations unless initialized?
71
- translations.keys
72
- end
73
-
74
- def reload!
75
- @initialized = false
76
- @translations = nil
77
- end
78
-
79
- protected
80
- def init_translations
81
- load_translations(*I18n.load_path.flatten)
82
- @initialized = true
83
- end
84
-
85
- def translations
86
- @translations ||= {}
87
- end
88
-
89
- # Looks up a translation from the translations hash. Returns nil if
90
- # eiher key is nil, or locale, scope or key do not exist as a key in the
91
- # nested translations hash. Splits keys or scopes containing dots
92
- # into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
93
- # <tt>%w(currency format)</tt>.
94
- def lookup(locale, key, scope = [], separator = nil)
95
- return unless key
96
- init_translations unless initialized?
97
- keys = I18n.send(:normalize_translation_keys, locale, key, scope, separator)
98
- keys.inject(translations) do |result, k|
99
- if (x = result[k.to_sym]).nil?
100
- return nil
101
- else
102
- x
103
- end
104
- end
105
- end
106
-
107
- # Evaluates defaults.
108
- # If given subject is an Array, it walks the array and returns the
109
- # first translation that can be resolved. Otherwise it tries to resolve
110
- # the translation directly.
111
- def default(locale, object, subject, options = {})
112
- options = options.dup.reject { |key, value| key == :default }
113
- case subject
114
- when Array
115
- subject.each do |subject|
116
- result = resolve(locale, object, subject, options) and return result
117
- end and nil
118
- else
119
- resolve(locale, object, subject, options)
120
- end
121
- end
122
-
123
- # Resolves a translation.
124
- # If the given subject is a Symbol, it will be translated with the
125
- # given options. If it is a Proc then it will be evaluated. All other
126
- # subjects will be returned directly.
127
- def resolve(locale, object, subject, options = {})
128
- case subject
129
- when Symbol
130
- translate(locale, subject, options)
131
- when Proc
132
- resolve(locale, object, subject.call(object, options), options = {})
133
- else
134
- subject
135
- end
136
- rescue MissingTranslationData
137
- nil
138
- end
139
-
140
- # Picks a translation from an array according to English pluralization
141
- # rules. It will pick the first translation if count is not equal to 1
142
- # and the second translation if it is equal to 1. Other backends can
143
- # implement more flexible or complex pluralization rules.
144
- def pluralize(locale, entry, count)
145
- return entry unless entry.is_a?(Hash) and count
146
-
147
- key = :zero if count == 0 && entry.has_key?(:zero)
148
- key ||= count == 1 ? :one : :other
149
- raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
150
- entry[key]
151
- end
152
-
153
- # Interpolates values into a given string.
154
- #
155
- # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X'
156
- # # => "file test.txt opened by {{user}}"
157
- #
158
- # Note that you have to double escape the <tt>\\</tt> when you want to escape
159
- # the <tt>{{...}}</tt> key in a string (once for the string and once for the
160
- # interpolation).
161
- def interpolate(locale, string, values = {})
162
- return string unless string.is_a?(String) && !values.empty?
163
-
164
- string.gsub(INTERPOLATION_SYNTAX_PATTERN) do
165
- escaped, key = $1, $2.to_sym
166
-
167
- if escaped
168
- key
169
- elsif RESERVED_KEYS.include?(key)
170
- raise ReservedInterpolationKey.new(key, string)
171
- else
172
- "%{#{key}}"
173
- end
174
- end % values
175
-
176
- rescue KeyError => e
177
- raise MissingInterpolationArgument.new(values, string)
178
- end
179
-
180
- # Loads a single translations file by delegating to #load_rb or
181
- # #load_yml depending on the file extension and directly merges the
182
- # data to the existing translations. Raises I18n::UnknownFileType
183
- # for all other file extensions.
184
- def load_file(filename)
185
- type = File.extname(filename).tr('.', '').downcase
186
- raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}")
187
- data = send :"load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash
188
- data.each { |locale, d| merge_translations(locale, d) }
189
- end
190
-
191
- # Loads a plain Ruby translations file. eval'ing the file must yield
192
- # a Hash containing translation data with locales as toplevel keys.
193
- def load_rb(filename)
194
- eval(IO.read(filename), binding, filename)
195
- end
196
-
197
- # Loads a YAML translations file. The data must have locales as
198
- # toplevel keys.
199
- def load_yml(filename)
200
- YAML::load(IO.read(filename))
201
- end
202
-
203
- # Deep merges the given translations hash with the existing translations
204
- # for the given locale
205
- def merge_translations(locale, data)
206
- locale = locale.to_sym
207
- translations[locale] ||= {}
208
- data = deep_symbolize_keys(data)
209
-
210
- # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
211
- merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
212
- translations[locale].merge!(data, &merger)
213
- end
214
-
215
- # Return a new hash with all keys and nested keys converted to symbols.
216
- def deep_symbolize_keys(hash)
217
- hash.inject({}) { |result, (key, value)|
218
- value = deep_symbolize_keys(value) if value.is_a?(Hash)
219
- result[(key.to_sym rescue key) || key] = value
220
- result
221
- }
222
- end
223
-
224
- # Flatten the given array once
225
- def flatten_once(array)
226
- result = []
227
- for element in array # a little faster than each
228
- result.push(*element)
229
- end
230
- result
231
- end
19
+ include Base
232
20
  end
233
21
  end
234
22
  end
@@ -0,0 +1,5 @@
1
+ Object.class_eval do
2
+ def meta_class
3
+ class << self; self; end
4
+ end
5
+ end unless Object.method_defined?(:meta_class)
@@ -1,3 +1,5 @@
1
+ # encoding: utf-8
2
+
1
3
  =begin
2
4
  heavily based on Masao Mutoh's gettext String interpolation extension
3
5
  http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb