i18n-js 2.1.2 → 3.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. checksums.yaml +7 -0
  2. data/.editorconfig +24 -0
  3. data/.gitignore +5 -4
  4. data/.npmignore +27 -0
  5. data/.travis.yml +37 -0
  6. data/Appraisals +20 -0
  7. data/CHANGELOG.md +354 -0
  8. data/Gemfile +1 -1
  9. data/README.md +872 -0
  10. data/Rakefile +19 -7
  11. data/app/assets/javascripts/i18n/filtered.js.erb +23 -0
  12. data/app/assets/javascripts/i18n/shims.js +208 -0
  13. data/app/assets/javascripts/i18n/translations.js +3 -0
  14. data/app/assets/javascripts/i18n.js +1077 -0
  15. data/gemfiles/i18n_0_6.gemfile +7 -0
  16. data/gemfiles/i18n_0_7.gemfile +7 -0
  17. data/gemfiles/i18n_0_8.gemfile +7 -0
  18. data/gemfiles/i18n_0_9.gemfile +7 -0
  19. data/gemfiles/i18n_1_0.gemfile +7 -0
  20. data/i18n-js.gemspec +11 -9
  21. data/lib/i18n/js/dependencies.rb +59 -0
  22. data/lib/i18n/js/engine.rb +87 -0
  23. data/lib/i18n/js/fallback_locales.rb +70 -0
  24. data/lib/{i18n-js → i18n/js}/middleware.rb +32 -9
  25. data/lib/i18n/js/private/hash_with_symbol_keys.rb +36 -0
  26. data/lib/i18n/js/segment.rb +88 -0
  27. data/lib/i18n/js/utils.rb +52 -0
  28. data/lib/i18n/js/version.rb +7 -0
  29. data/lib/i18n/js.rb +242 -0
  30. data/lib/i18n-js.rb +1 -177
  31. data/lib/rails/generators/i18n/js/config/config_generator.rb +19 -0
  32. data/{config → lib/rails/generators/i18n/js/config/templates}/i18n-js.yml +11 -6
  33. data/lib/tasks/export.rake +8 -0
  34. data/package.json +25 -0
  35. data/spec/fixtures/custom_path.yml +5 -0
  36. data/spec/fixtures/default.yml +5 -0
  37. data/spec/fixtures/erb.yml +5 -0
  38. data/spec/fixtures/except_condition.yml +7 -0
  39. data/spec/fixtures/js_export_dir_custom.yml +7 -0
  40. data/spec/fixtures/js_export_dir_none.yml +6 -0
  41. data/spec/fixtures/js_extend_parent.yml +6 -0
  42. data/spec/fixtures/js_extend_segment.yml +6 -0
  43. data/spec/fixtures/js_file_per_locale.yml +7 -0
  44. data/spec/fixtures/js_file_per_locale_with_fallbacks_as_default_locale_symbol.yml +4 -0
  45. data/spec/fixtures/js_file_per_locale_with_fallbacks_as_hash.yml +6 -0
  46. data/spec/fixtures/js_file_per_locale_with_fallbacks_as_locale.yml +4 -0
  47. data/spec/fixtures/js_file_per_locale_with_fallbacks_as_locale_without_fallback_translations.yml +4 -0
  48. data/spec/fixtures/js_file_per_locale_with_fallbacks_enabled.yml +4 -0
  49. data/spec/fixtures/js_file_per_locale_without_fallbacks.yml +4 -0
  50. data/spec/fixtures/js_file_with_namespace_and_pretty_print.yml +7 -0
  51. data/spec/fixtures/js_sort_translation_keys_false.yml +6 -0
  52. data/spec/fixtures/js_sort_translation_keys_true.yml +6 -0
  53. data/spec/{resources → fixtures}/locales.yml +13 -1
  54. data/spec/fixtures/multiple_conditions.yml +7 -0
  55. data/spec/fixtures/multiple_conditions_per_locale.yml +7 -0
  56. data/spec/fixtures/multiple_files.yml +7 -0
  57. data/spec/{resources → fixtures}/no_config.yml +0 -0
  58. data/spec/fixtures/no_scope.yml +4 -0
  59. data/spec/fixtures/simple_scope.yml +5 -0
  60. data/spec/js/currency.spec.js +62 -0
  61. data/spec/js/current_locale.spec.js +19 -0
  62. data/spec/js/dates.spec.js +265 -0
  63. data/spec/js/defaults.spec.js +31 -0
  64. data/spec/js/extend.spec.js +110 -0
  65. data/spec/js/interpolation.spec.js +124 -0
  66. data/spec/js/jasmine/MIT.LICENSE +20 -0
  67. data/spec/js/jasmine/jasmine-html.js +190 -0
  68. data/spec/js/jasmine/jasmine.css +166 -0
  69. data/spec/js/jasmine/jasmine.js +2476 -0
  70. data/spec/js/jasmine/jasmine_favicon.png +0 -0
  71. data/spec/js/locales.spec.js +31 -0
  72. data/spec/js/localization.spec.js +48 -0
  73. data/spec/js/numbers.spec.js +170 -0
  74. data/spec/js/placeholder.spec.js +24 -0
  75. data/spec/js/pluralization.spec.js +211 -0
  76. data/spec/js/prepare_options.spec.js +41 -0
  77. data/spec/js/require.js +2083 -0
  78. data/spec/js/specs.html +49 -0
  79. data/spec/js/specs_requirejs.html +72 -0
  80. data/spec/js/translate.spec.js +277 -0
  81. data/spec/js/translations.js +164 -0
  82. data/spec/js/utility_functions.spec.js +20 -0
  83. data/spec/ruby/i18n/js/fallback_locales_spec.rb +84 -0
  84. data/spec/ruby/i18n/js/segment_spec.rb +157 -0
  85. data/spec/ruby/i18n/js/utils_spec.rb +106 -0
  86. data/spec/ruby/i18n/js_spec.rb +627 -0
  87. data/spec/spec_helper.rb +55 -14
  88. data/yarn.lock +131 -0
  89. metadata +188 -96
  90. data/.rspec +0 -1
  91. data/Gemfile.lock +0 -51
  92. data/README.rdoc +0 -305
  93. data/lib/i18n-js/engine.rb +0 -62
  94. data/lib/i18n-js/railtie.rb +0 -13
  95. data/lib/i18n-js/rake.rb +0 -16
  96. data/lib/i18n-js/version.rb +0 -10
  97. data/spec/i18n_spec.js +0 -768
  98. data/spec/i18n_spec.rb +0 -205
  99. data/spec/resources/custom_path.yml +0 -4
  100. data/spec/resources/default.yml +0 -4
  101. data/spec/resources/js_file_per_locale.yml +0 -3
  102. data/spec/resources/multiple_conditions.yml +0 -6
  103. data/spec/resources/multiple_files.yml +0 -6
  104. data/spec/resources/no_scope.yml +0 -3
  105. data/spec/resources/simple_scope.yml +0 -4
  106. data/vendor/assets/javascripts/i18n/translations.js.erb +0 -7
  107. data/vendor/assets/javascripts/i18n.js +0 -450
data/README.md ADDED
@@ -0,0 +1,872 @@
1
+ # I18n.js
2
+
3
+ [![Gem Version](http://img.shields.io/gem/v/i18n-js.svg?style=flat-square)](http://badge.fury.io/rb/i18n-js)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
5
+
6
+ [![Build Status](http://img.shields.io/travis/fnando/i18n-js.svg?style=flat-square)](https://travis-ci.org/fnando/i18n-js)
7
+ [![Dependency Status](http://img.shields.io/gemnasium/fnando/i18n-js.svg?style=flat-square)](https://gemnasium.com/fnando/i18n-js)
8
+ [![Code Climate](http://img.shields.io/codeclimate/github/fnando/i18n-js.svg?style=flat-square)](https://codeclimate.com/github/fnando/i18n-js)
9
+
10
+ [![Gitter](https://img.shields.io/badge/gitter-join%20chat-1dce73.svg?style=flat-square)](https://gitter.im/fnando/i18n-js)
11
+
12
+ It's a small library to provide the Rails I18n translations on the JavaScript.
13
+
14
+ Features:
15
+
16
+ - Pluralization
17
+ - Date/Time localization
18
+ - Number localization
19
+ - Locale fallback
20
+ - Asset pipeline support
21
+ - Lots more! :)
22
+
23
+ ## Version Notice
24
+ The `master` branch (including this README) is for latest `3.0.0` instead of `2.x`.
25
+
26
+
27
+ ## Usage
28
+
29
+ ### Installation
30
+
31
+ #### Rails app
32
+
33
+ Add the gem to your Gemfile.
34
+ ```ruby
35
+ gem "i18n-js"
36
+ ```
37
+
38
+ #### Rails app with [Asset Pipeline](http://guides.rubyonrails.org/asset_pipeline.html)
39
+
40
+ If you're using the [asset pipeline](http://guides.rubyonrails.org/asset_pipeline.html),
41
+ then you must add the following line to your `app/assets/javascripts/application.js`.
42
+
43
+ ```javascript
44
+ //
45
+ // This is optional (in case you have `I18n is not defined` error)
46
+ // If you want to put this line, you must put it BEFORE `i18n/translations`
47
+ //= require i18n
48
+ // Some people even need to add the extension to make it work, see https://github.com/fnando/i18n-js/issues/283
49
+ //= require i18n.js
50
+ //
51
+ // This is a must
52
+ //= require i18n/translations
53
+ ```
54
+
55
+ #### Rails app without [Asset Pipeline](http://guides.rubyonrails.org/asset_pipeline.html)
56
+
57
+
58
+ First, put this in your `application.html` (layout file).
59
+ Then get the JS files following the instructions below.
60
+ ```erb
61
+ <%# This is just an example, you can put `i18n.js` and `translations.js` anywhere you like %>
62
+ <%# Unlike the Asset Pipeline example, you need to require both **in order** %>
63
+ <%= javascript_include_tag "i18n" %>
64
+ <%= javascript_include_tag "translations", skip_pipeline: true %>
65
+ ```
66
+
67
+ **There are two ways to get `translations.js` (For Rails app without Asset Pipeline).**
68
+
69
+ 1. This `translations.js` file can be automatically generated by the `I18n::JS::Middleware`.
70
+ Just add `config.middleware.use I18n::JS::Middleware` to your `config/application.rb` file.
71
+ 2. If you can't or prefer not to generate this file,
72
+ you can move the middleware line to your `config/environments/development.rb` file
73
+ and run `rake i18n:js:export` before deploying.
74
+ This will export all translation files, including the custom scopes
75
+ you may have defined on `config/i18n-js.yml`.
76
+ If `I18n.available_locales` is set (e.g. in your Rails `config/application.rb` file)
77
+ then only the specified locales will be exported.
78
+ Current version of `i18n.js` will also be exported to avoid version mismatching by downloading.
79
+
80
+ #### Export Configuration (For translations)
81
+
82
+ Exported translation files generated by `I18n::JS::Middleware` or `rake i18n:js:export` can be customized with config file `config/i18n-js.yml`
83
+ (use `rails generate i18n:js:config` to create it).
84
+ You can even get more files generated to different folders and with different translations to best suit your needs.
85
+ The config file also affects developers using Asset Pipeline to require translations.
86
+ Except the option `file`, since all translations are required by adding `//= require i18n/translations`.
87
+
88
+ Examples:
89
+ ```yaml
90
+ translations:
91
+ - file: 'public/javascripts/path-to-your-messages-file.js'
92
+ only: '*.date.formats'
93
+ - file: 'public/javascripts/path-to-your-second-file.js'
94
+ only: ['*.activerecord', '*.admin.*.title']
95
+ ```
96
+
97
+ If `only` is omitted all the translations will be saved. Also, make sure you add that initial `*`; it specifies that all languages will be exported. If you want to export only one language, you can do something like this:
98
+ ```yaml
99
+ translations:
100
+ - file: 'public/javascripts/en.js'
101
+ only: 'en.*'
102
+ - file: 'public/javascripts/pt-BR.js'
103
+ only: 'pt-BR.*'
104
+ ```
105
+
106
+ Optionally, you can auto generate a translation file per available locale if you specify the `%{locale}` placeholder.
107
+ ```yaml
108
+ translations:
109
+ - file: "public/javascripts/i18n/%{locale}.js"
110
+ only: '*'
111
+ - file: "public/javascripts/frontend/i18n/%{locale}.js"
112
+ only: ['*.frontend', '*.users.*']
113
+ ```
114
+
115
+ You can also include ERB in your config file.
116
+ ```yaml
117
+ translations:
118
+ <% Widgets.each do |widget| %>
119
+ - file: <%= "'#{widget.file}'" %>
120
+ only: <%= "'#{widget.only}'" %>
121
+ <% end %>
122
+ ```
123
+
124
+ You are able to exclude certain phrases or whole groups of phrases by
125
+ specifying the YAML key(s) in the `except` configuration option. The outputted
126
+ JS translations file (exported or generated by the middleware) will omit any
127
+ keys listed in `except` configuration param:
128
+
129
+ ```yaml
130
+ translations:
131
+ - except: ['*.active_admin', '*.ransack', '*.activerecord.errors']
132
+ ```
133
+
134
+
135
+ #### Export Configuration (For other things)
136
+
137
+ - `I18n::JS.config_file_path`
138
+ Expected Type: `String`
139
+ Default: `config/i18n-js.yml`
140
+ Behaviour: Try to read the config file from that location
141
+
142
+ - `I18n::JS.export_i18n_js_dir_path`
143
+ Expected Type: `String`
144
+ Default: `public/javascripts`
145
+ Behaviour:
146
+ - Any `String`: considered as a relative path for a folder to `Rails.root` and export `i18n.js` to that folder for `rake i18n:js:export`
147
+ - Any non-`String` (`nil`, `false`, `:none`, etc): Disable `i18n.js` exporting
148
+
149
+ - `I18n::JS.sort_translation_keys`
150
+ Expected Type: `Boolean`
151
+ Default: `true`
152
+ Behaviour:
153
+ - Sets whether or not to deep sort all translation keys in order to generate identical output for the same translations
154
+ - Set to true to ensure identical asset fingerprints for the asset pipeline
155
+
156
+ - You may also set `export_i18n_js` and `sort_translation_keys` in your config file, e.g.:
157
+
158
+ ```yaml
159
+ export_i18n_js: false
160
+ # OR
161
+ export_i18n_js: "my/path"
162
+
163
+ sort_translation_keys: false
164
+
165
+ translations:
166
+ - ...
167
+ ```
168
+
169
+ To find more examples on how to use the configuration file please refer to the tests.
170
+
171
+ #### Fallbacks
172
+
173
+ If you specify the `fallbacks` option, you will be able to fill missing translations with those inside fallback locale(s).
174
+ Default value is `true`.
175
+
176
+ Examples:
177
+ ```yaml
178
+ fallbacks: true
179
+
180
+ translations:
181
+ - file: "public/javascripts/i18n/%{locale}.js"
182
+ only: '*'
183
+ ```
184
+ This will enable merging fallbacks into each file. (set to `false` to disable).
185
+ If you use `I18n` with fallbacks, the fallbacks defined there will be used.
186
+ Otherwise `I18n.default_locale` will be used.
187
+
188
+ ```yaml
189
+ fallbacks: :de
190
+
191
+ translations:
192
+ - file: "public/javascripts/i18n/%{locale}.js"
193
+ only: '*'
194
+ ```
195
+ Here, the specified locale `:de` will be used as fallback for all locales.
196
+
197
+ ```yaml
198
+ fallbacks:
199
+ fr: ["de", "en"]
200
+ de: "en"
201
+
202
+ translations:
203
+ - file: "public/javascripts/i18n/%{locale}.js"
204
+ only: '*'
205
+ ```
206
+ Fallbacks defined will be used, if not defined (e.g. `:pl`) `I18n.fallbacks` or `I18n.default_locale` will be used.
207
+
208
+ ```yaml
209
+ fallbacks: :default_locale
210
+
211
+ translations:
212
+ - file: "public/javascripts/i18n/%{locale}.js"
213
+ only: '*'
214
+ ```
215
+ Setting the option to `:default_locale` will enforce the fallback to use the `I18n.default_locale`, ignoring `I18n.fallbacks`.
216
+
217
+ Examples:
218
+ ```yaml
219
+ fallbacks: false
220
+
221
+ translations:
222
+ - file: "public/javascripts/i18n/%{locale}.js"
223
+ only: '*'
224
+ ```
225
+ You must disable this feature by setting the option to `false`.
226
+
227
+ To find more examples on how to use the configuration file please refer to the tests.
228
+
229
+
230
+ #### Namespace
231
+
232
+ Setting the `namespace` option will change the namespace of the output Javascript file to something other than `I18n`.
233
+ This can be useful in no-conflict scenarios. Example:
234
+
235
+ ```yaml
236
+ translations:
237
+ - file: "public/javascripts/i18n/translations.js"
238
+ namespace: "MyNamespace"
239
+ ```
240
+
241
+ will create:
242
+
243
+ ```
244
+ MyNamespace.translations || (MyNamespace.translations = {});
245
+ MyNamespace.translations["en"] = { ... }
246
+ ```
247
+
248
+
249
+ #### Pretty Print
250
+
251
+ Set the `pretty_print` option if you would like whitespace and indentation in your output file (default: false)
252
+
253
+ ```yaml
254
+ translations:
255
+ - file: "public/javascripts/i18n/translations.js"
256
+ pretty_print: true
257
+ ```
258
+
259
+
260
+ #### Javascript Deep Merge (:js_extend option)
261
+
262
+ By default, the output file Javascript will call the `I18n.extend` method to ensure that newly loaded locale
263
+ files are deep-merged with any locale data already in memory. To disable this either globally or per-file,
264
+ set the `js_extend` option to false
265
+
266
+ ```yaml
267
+ js_extend: false # this will disable Javascript I18n.extend globally
268
+ translations:
269
+ - file: "public/javascripts/i18n/translations.js"
270
+ js_extend: false # this will disable Javascript I18n.extend for this file
271
+ ```
272
+
273
+
274
+ #### Vanilla JavaScript
275
+
276
+ Just add the `i18n.js` file to your page. You'll have to build the translations object
277
+ by hand or using your favorite programming language. More info below.
278
+
279
+
280
+ #### Via NPM with webpack and CommonJS
281
+
282
+
283
+ Add the following line to your package.json dependencies
284
+ where version is the version you want
285
+ ```javascript
286
+ "i18n-js": "{version_constraint}"
287
+
288
+ // Or if you want unreleased version
289
+ // npm install requires it to be the gzipped tarball, see [npm install](https://www.npmjs.org/doc/cli/npm-install.html)
290
+ "i18n-js": "https://github.com/fnando/i18n-js/archive/{tag_name_or_branch_name_or_commit_sha}.tar.gz"
291
+ ```
292
+ Run npm install then use via
293
+ ```javascript
294
+ var i18n = require("i18n-js");
295
+ ```
296
+
297
+
298
+ ### Setting up
299
+
300
+ You **don't** need to set up a thing. The default settings will work just okay. But if you want to split translations into several files or specify specific contexts, you can follow the rest of this setting up section.
301
+
302
+ Set your locale is easy as
303
+ ```javascript
304
+ I18n.defaultLocale = "pt-BR";
305
+ I18n.locale = "pt-BR";
306
+ I18n.currentLocale();
307
+ // pt-BR
308
+ ```
309
+
310
+ **NOTE:** You can now apply your configuration **before I18n** is loaded like this:
311
+ ```javascript
312
+ I18n = {} // You must define this object in top namespace, which should be `window`
313
+ I18n.defaultLocale = "pt-BR";
314
+ I18n.locale = "pt-BR";
315
+
316
+ // Load I18n from `i18n.js`, `application.js` or whatever
317
+
318
+ I18n.currentLocale();
319
+ // pt-BR
320
+ ```
321
+
322
+ In practice, you'll have something like the following in your `application.html.erb`:
323
+
324
+ ```erb
325
+ <script type="text/javascript">
326
+ I18n.defaultLocale = "<%= I18n.default_locale %>";
327
+ I18n.locale = "<%= I18n.locale %>";
328
+ </script>
329
+ ```
330
+
331
+ You can use translate your messages:
332
+
333
+ ```javascript
334
+ I18n.t("some.scoped.translation");
335
+ // or translate with explicit setting of locale
336
+ I18n.t("some.scoped.translation", {locale: "fr"});
337
+ ```
338
+
339
+ You can also interpolate values:
340
+
341
+ ```javascript
342
+ I18n.t("hello", {name: "John Doe"});
343
+ ```
344
+ You can set default values for missing scopes:
345
+ ```javascript
346
+ // simple translation
347
+ I18n.t("some.missing.scope", {defaultValue: "A default message"});
348
+
349
+ // with interpolation
350
+ I18n.t("noun", {defaultValue: "I'm a {{noun}}", noun: "Mac"});
351
+ ```
352
+
353
+ You can also provide a list of default fallbacks for missing scopes:
354
+
355
+ ```javascript
356
+ // As a scope
357
+ I18n.t("some.missing.scope", {defaults: [{scope: "some.existing.scope"}]});
358
+
359
+ // As a simple translation
360
+ I18n.t("some.missing.scope", {defaults: [{message: "Some message"}]});
361
+ ```
362
+
363
+ Default values must be provided as an array of hashs where the key is the
364
+ type of translation desired, a `scope` or a `message`. The translation returned
365
+ will be either the first scope recognized, or the first message defined.
366
+
367
+ The translation will fallback to the `defaultValue` translation if no scope
368
+ in `defaults` matches and if no default of type `message` is found.
369
+
370
+ Translation fallback can be enabled by enabling the `I18n.fallbacks` option:
371
+
372
+ ```erb
373
+ <script type="text/javascript">
374
+ I18n.fallbacks = true;
375
+ </script>
376
+ ```
377
+
378
+ By default missing translations will first be looked for in less
379
+ specific versions of the requested locale and if that fails by taking
380
+ them from your `I18n.defaultLocale`.
381
+
382
+ ```javascript
383
+ // if I18n.defaultLocale = "en" and translation doesn't exist
384
+ // for I18n.locale = "de-DE" this key will be taken from "de" locale scope
385
+ // or, if that also doesn't exist, from "en" locale scope
386
+ I18n.t("some.missing.scope");
387
+ ```
388
+
389
+ Custom fallback rules can also be specified for a particular language. There
390
+ are three different ways of doing it so:
391
+
392
+ ```javascript
393
+ I18n.locales.no = ["nb", "en"];
394
+ I18n.locales.no = "nb";
395
+ I18n.locales.no = function(locale){ return ["nb"]; };
396
+ ```
397
+
398
+ By default a missing translation will be displayed as
399
+
400
+ [missing "name of scope" translation]
401
+
402
+ While you are developing or if you do not want to provide a translation
403
+ in the default language you can set
404
+
405
+ ```javascript
406
+ I18n.missingBehaviour='guess';
407
+ ```
408
+
409
+ this will take the last section of your scope and guess the intended value.
410
+ Camel case becomes lower cased text and underscores are replaced with space
411
+
412
+ questionnaire.whatIsYourFavorite_ChristmasPresent
413
+
414
+ becomes "what is your favorite Christmas present"
415
+
416
+ In order to still detect untranslated strings, you can
417
+ i18n.missingTranslationPrefix to something like:
418
+ ```javascript
419
+ I18n.missingTranslationPrefix = 'EE: ';
420
+ ```
421
+
422
+ And result will be:
423
+ ```javascript
424
+ "EE: what is your favorite Christmas present"
425
+ ```
426
+
427
+ This will help you doing automated tests against your localisation assets.
428
+
429
+ Some people prefer returning `null` for missing translation:
430
+ ```javascript
431
+ I18n.missingTranslation = function () { return undefined; };
432
+ ```
433
+
434
+ Pluralization is possible as well and by default provides English rules:
435
+
436
+ ```javascript
437
+ I18n.t("inbox.counting", {count: 10}); // You have 10 messages
438
+ ```
439
+
440
+ The sample above expects the following translation:
441
+
442
+ ```yaml
443
+ en:
444
+ inbox:
445
+ counting:
446
+ one: You have 1 new message
447
+ other: You have {{count}} new messages
448
+ zero: You have no messages
449
+ ```
450
+
451
+ **NOTE:** Rails I18n recognizes the `zero` option.
452
+
453
+ If you need special rules just define them for your language, for example Russian, just add a new pluralizer:
454
+
455
+ ```javascript
456
+ I18n.pluralization["ru"] = function (count) {
457
+ var key = count % 10 == 1 && count % 100 != 11 ? "one" : [2, 3, 4].indexOf(count % 10) >= 0 && [12, 13, 14].indexOf(count % 100) < 0 ? "few" : count % 10 == 0 || [5, 6, 7, 8, 9].indexOf(count % 10) >= 0 || [11, 12, 13, 14].indexOf(count % 100) >= 0 ? "many" : "other";
458
+ return [key];
459
+ };
460
+ ```
461
+
462
+ You can find all rules on <http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html>.
463
+
464
+ If you're using the same scope over and over again, you may use the `scope` option.
465
+
466
+ ```javascript
467
+ var options = {scope: "activerecord.attributes.user"};
468
+
469
+ I18n.t("name", options);
470
+ I18n.t("email", options);
471
+ I18n.t("username", options);
472
+ ```
473
+
474
+ You can also provide an array as scope.
475
+
476
+ ```javascript
477
+ // use the greetings.hello scope
478
+ I18n.t(["greetings", "hello"]);
479
+ ```
480
+
481
+ #### Number formatting
482
+
483
+ Similar to Rails helpers, you have localized number and currency formatting.
484
+
485
+ ```javascript
486
+ I18n.l("currency", 1990.99);
487
+ // $1,990.99
488
+
489
+ I18n.l("number", 1990.99);
490
+ // 1,990.99
491
+
492
+ I18n.l("percentage", 123.45);
493
+ // 123.450%
494
+ ```
495
+
496
+ To have more control over number formatting, you can use the
497
+ `I18n.toNumber`, `I18n.toPercentage`, `I18n.toCurrency` and `I18n.toHumanSize`
498
+ functions.
499
+
500
+ ```javascript
501
+ I18n.toNumber(1000); // 1,000.000
502
+ I18n.toCurrency(1000); // $1,000.00
503
+ I18n.toPercentage(100); // 100.000%
504
+ ```
505
+
506
+ The `toNumber` and `toPercentage` functions accept the following options:
507
+
508
+ - `precision`: defaults to `3`
509
+ - `separator`: defaults to `.`
510
+ - `delimiter`: defaults to `,`
511
+ - `strip_insignificant_zeros`: defaults to `false`
512
+
513
+ See some number formatting examples:
514
+
515
+ ```javascript
516
+ I18n.toNumber(1000, {precision: 0}); // 1,000
517
+ I18n.toNumber(1000, {delimiter: ".", separator: ","}); // 1.000,000
518
+ I18n.toNumber(1000, {delimiter: ".", precision: 0}); // 1.000
519
+ ```
520
+
521
+ The `toCurrency` function accepts the following options:
522
+
523
+ - `precision`: sets the level of precision
524
+ - `separator`: sets the separator between the units
525
+ - `delimiter`: sets the thousands delimiter
526
+ - `format`: sets the format of the output string
527
+ - `unit`: sets the denomination of the currency
528
+ - `strip_insignificant_zeros`: defaults to `false`
529
+ - `sign_first`: defaults to `true`
530
+
531
+ You can provide only the options you want to override:
532
+
533
+ ```javascript
534
+ I18n.toCurrency(1000, {precision: 0}); // $1,000
535
+ ```
536
+
537
+ The `toHumanSize` function accepts the following options:
538
+
539
+ - `precision`: defaults to `1`
540
+ - `separator`: defaults to `.`
541
+ - `delimiter`: defaults to `""`
542
+ - `strip_insignificant_zeros`: defaults to `false`
543
+ - `format`: defaults to `%n%u`
544
+
545
+ <!---->
546
+
547
+ ```javascript
548
+ I18n.toHumanSize(1234); // 1KB
549
+ I18n.toHumanSize(1234 * 1024); // 1MB
550
+ ```
551
+
552
+
553
+ #### Date formatting
554
+
555
+ ```javascript
556
+ // accepted formats
557
+ I18n.l("date.formats.short", "2009-09-18"); // yyyy-mm-dd
558
+ I18n.l("time.formats.short", "2009-09-18 23:12:43"); // yyyy-mm-dd hh:mm:ss
559
+ I18n.l("time.formats.short", "2009-11-09T18:10:34"); // JSON format with local Timezone (part of ISO-8601)
560
+ I18n.l("time.formats.short", "2009-11-09T18:10:34Z"); // JSON format in UTC (part of ISO-8601)
561
+ I18n.l("date.formats.short", 1251862029000); // Epoch time
562
+ I18n.l("date.formats.short", "09/18/2009"); // mm/dd/yyyy
563
+ I18n.l("date.formats.short", (new Date())); // Date object
564
+ ```
565
+
566
+ You can also add placeholders to the date format:
567
+
568
+ ```javascript
569
+ I18n.translations["en"] = {
570
+ date: {
571
+ formats: {
572
+ ordinal_day: "%B %{day}"
573
+ }
574
+ }
575
+ }
576
+ I18n.l("date.formats.ordinal_day", "2009-09-18", { day: '18th' }); // Sep 18th
577
+ ```
578
+
579
+ If you prefer, you can use the `I18n.strftime` function to format dates.
580
+
581
+ ```javascript
582
+ var date = new Date();
583
+ I18n.strftime(date, "%d/%m/%Y");
584
+ ```
585
+
586
+ The accepted formats are:
587
+
588
+ %a - The abbreviated weekday name (Sun)
589
+ %A - The full weekday name (Sunday)
590
+ %b - The abbreviated month name (Jan)
591
+ %B - The full month name (January)
592
+ %d - Day of the month (01..31)
593
+ %-d - Day of the month (1..31)
594
+ %H - Hour of the day, 24-hour clock (00..23)
595
+ %-H - Hour of the day, 24-hour clock (0..23)
596
+ %I - Hour of the day, 12-hour clock (01..12)
597
+ %-I - Hour of the day, 12-hour clock (1..12)
598
+ %m - Month of the year (01..12)
599
+ %-m - Month of the year (1..12)
600
+ %M - Minute of the hour (00..59)
601
+ %-M - Minute of the hour (0..59)
602
+ %p - Meridian indicator (AM or PM)
603
+ %S - Second of the minute (00..60)
604
+ %-S - Second of the minute (0..60)
605
+ %w - Day of the week (Sunday is 0, 0..6)
606
+ %y - Year without a century (00..99)
607
+ %-y - Year without a century (0..99)
608
+ %Y - Year with century
609
+ %z - Timezone offset (+0545)
610
+
611
+ Check out `spec/*.spec.js` files for more examples!
612
+
613
+ #### Using pluralization and number formatting together
614
+ Sometimes you might want to display translation with formatted number, like adding thousand delimiters to displayed number
615
+ You can do this:
616
+ ```json
617
+ {
618
+ "en": {
619
+ "point": {
620
+ "one": "1 Point",
621
+ "other": "{{formatted_number}} Points",
622
+ "zero": "0 Points"
623
+ }
624
+ }
625
+ }
626
+ ```
627
+ ```js
628
+ var point_in_number = 1000;
629
+ I18n.t('point', { count: point_in_number, formatted_number: I18n.toNumber(point_in_number) });
630
+ ```
631
+ Output should be `1,000 points`
632
+
633
+
634
+ ## Using multiple exported translation files on a page.
635
+ This method is useful for very large apps where a single contained translations.js file is not desirable. Examples would be a global translations file and a more specific route translation file.
636
+
637
+ ### Rails without asset pipeline
638
+ 1. Setup your `config/i18n-js.yml` to have multiple files and try to minimize any overlap.
639
+
640
+ ```yaml
641
+ sort_translation_keys: true
642
+ fallbacks: false
643
+
644
+ translations:
645
+ + file: "app/assets/javascript/nls/welcome.js"
646
+ only:
647
+ + '*.welcome.*'
648
+
649
+ + file: "app/assets/javascript/nls/albums.js"
650
+ only:
651
+ + '*.albums.*'
652
+
653
+ + file: "app/assets/javascript/nls/global.js"
654
+ only:
655
+ + '*'
656
+ # Exempt any routes specific translations from being
657
+ # included in the global translation file
658
+ except:
659
+ + '*.welcome.*'
660
+ + '*.albums.*'
661
+ ```
662
+ When `rake i18n:js:export` is executed it will create 3 translations files that can be loaded via the `javascript_include_tag`
663
+
664
+ 2. Add the `javascript_include_tag` to your layout and to any route specific files that will require it.
665
+ ```ruby
666
+ # views/layouts/application.html.erb
667
+ <%= javascript_include_tag(
668
+ "i18n"
669
+ "nls/global"
670
+ ) %>
671
+ ```
672
+ and in the route specific
673
+
674
+ ```ruby
675
+ # views/welcome/index.html.erb
676
+ <%= javascript_include_tag(
677
+ "nls/welcome"
678
+ ) %>
679
+ ```
680
+
681
+ 3. Make sure that you add these files to your `config/application.rb`
682
+
683
+ ```ruby
684
+ config.assets.precompile += %w(
685
+ i18n
686
+ nls/*
687
+ )
688
+ ```
689
+
690
+ ### Using require.js / r.js
691
+
692
+ To use this with require.js we are only going to change a few things from above.
693
+
694
+ 1. In your `config/i18n-js.yml` we need to add a better location for the i18n to be exported. You want to use this location so that it can be properly precompiled by r.js.
695
+
696
+ ```yaml
697
+ export_i18n_js: "app/assets/javascript/nls"
698
+ ```
699
+
700
+ 2. In your `config/require.yml` we need to add a map, shim all the translations, and include them into the appropriate modules
701
+
702
+ ```yaml
703
+ # In your maps add (if you do not have this you will need to add it)
704
+ map:
705
+ '*':
706
+ i18n: 'nls/i18n'
707
+
708
+ # In your shims
709
+ shims:
710
+ nls/welcome:
711
+ deps:
712
+ + i18n
713
+
714
+ nls/global:
715
+ deps:
716
+ + i18n
717
+
718
+ # Finally in your modules
719
+ modules:
720
+ + name: 'application'
721
+ include:
722
+ + i18n
723
+ + 'nls/global'
724
+
725
+ + name: 'welcome'
726
+ exclude:
727
+ + application
728
+ include:
729
+ + 'nls/welcome'
730
+ ```
731
+ 3. When `rake assets:precompile` is executed it will optimize the translations into the correct modules so they are loaded with their assigned module, and loading them with requirejs is as simple as requiring any other shim.
732
+
733
+ ```javascript
734
+ define(['welcome/other_asset','nls/welcome'], function (otherAsset){
735
+ // ...
736
+ });
737
+ ```
738
+ 4. (optional) As an additional configuration we can make a task to be run before the requirejs optimizer. This will allow any automated scripts that run the requirejs optimizer to export the strings before we run r.js
739
+
740
+ ```rake
741
+ # lib/tasks/i18n.rake
742
+ Rake::Task[:'i18n:js:export'].prerequisites.clear
743
+ task :'i18n:js:export' => :'i18n:js:before_export'
744
+ task :'requirejs:precompile:external' => :'i18n:js:export'
745
+
746
+ namespace :i18n do
747
+ namespace :js do
748
+ task :before_export => :'assets:environment' do
749
+ I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{yml,rb}')]
750
+ I18n.backend.load_translations
751
+ end
752
+ end
753
+ end
754
+ ```
755
+
756
+ ## Using I18n.js with other languages (Python, PHP, ...)
757
+
758
+ The JavaScript library is language agnostic; so you can use it with PHP, Python, [your favorite language here].
759
+ The only requirement is that you need to set the `translations` attribute like following:
760
+
761
+ ```javascript
762
+ I18n.translations = {};
763
+
764
+ I18n.translations["en"] = {
765
+ message: "Some special message for you"
766
+ }
767
+
768
+ I18n.translations["pt-BR"] = {
769
+ message: "Uma mensagem especial para você"
770
+ }
771
+ ```
772
+
773
+
774
+ ## Known Issues
775
+
776
+ ### Missing translations in precompiled file(s) after adding any new locale file
777
+
778
+ Due to the design of `sprockets`:
779
+
780
+ - `depend_on` only takes file paths, not directory paths
781
+ - registered `preprocessors` are only run when the fingerprint of any asset file, including `.erb` files, is changed
782
+
783
+ This means that new locale files will not be detected, and so they will not trigger a i18n-js refresh. There are a few approaches to work around this:
784
+
785
+ 1. You can force i18n-js to update its translations by completely clearing the assets cache. Use one of the following:
786
+
787
+ ```bash
788
+ $ rake assets:clobber
789
+ # Or, with older versions of Rails:
790
+ $ rake tmp:cache:clear
791
+ ```
792
+
793
+ These commands will remove *all* fingerprinted assets, and you will have to recompile them with
794
+
795
+ ```bash
796
+ $ rake assets:precompile
797
+ ```
798
+
799
+ or similar commands. If you are precompiling assets on the target machine(s), cached pages may be broken by this, so they will need to be refreshed.
800
+
801
+ 2. You can change something in a different locale file.
802
+
803
+ 3. Finally, you can change `config.assets.version`.
804
+
805
+ **Note:** See issue [#213](https://github.com/fnando/i18n-js/issues/213) for more details and discussion of this issue.
806
+
807
+ ### Translations in JS are not updated when Sprockets not loaded before this gem
808
+
809
+ The "rails engine" declaration will try to detect existence of "sprockets" before adding the initailizer
810
+ If sprockets is loaded after this gem, the preprocessor for
811
+ making JS translations file cache to depend on content of locale files will not be hooked.
812
+ So ensure sprockets is loaded before this gem like moving entry of sprockets in Gemfile or adding "require" statements for sprockets somewhere.
813
+
814
+ **Note:** See issue [#404](https://github.com/fnando/i18n-js/issues/404) for more details and discussion of this issue.
815
+
816
+
817
+ ## Maintainer
818
+
819
+ - Nando Vieira - <http://nandovieira.com.br>
820
+
821
+ ## Contributing
822
+
823
+ Once you've made your great commits:
824
+
825
+ 1. [Fork](http://help.github.com/forking/) I18n.js
826
+ 2. Create a branch with a clear name
827
+ 3. Make your changes (Please also add/change spec, README and CHANGELOG if applicable)
828
+ 4. Push changes to the created branch
829
+ 5. [Create an Pull Request](http://github.com/fnando/i18n-js/pulls)
830
+ 6. That's it!
831
+
832
+ Please respect the indentation rules and code style.
833
+ And use 2 spaces, not tabs. And don't touch the versioning thing.
834
+
835
+ ## Running tests
836
+
837
+ You can run I18n tests using Node.js or your browser.
838
+
839
+ To use Node.js, install the `jasmine-node` library:
840
+
841
+ $ npm install jasmine-node
842
+
843
+ Then execute the following command from the lib's root directory:
844
+
845
+ $ npm test
846
+
847
+ To run using your browser, just open the `spec/js/specs.html` file.
848
+
849
+ You can run both Ruby and JavaScript specs with `rake spec`.
850
+
851
+ ## License
852
+
853
+ (The MIT License)
854
+
855
+ Permission is hereby granted, free of charge, to any person obtaining
856
+ a copy of this software and associated documentation files (the
857
+ 'Software'), to deal in the Software without restriction, including
858
+ without limitation the rights to use, copy, modify, merge, publish,
859
+ distribute, sublicense, and/or sell copies of the Software, and to
860
+ permit persons to whom the Software is furnished to do so, subject to
861
+ the following conditions:
862
+
863
+ The above copyright notice and this permission notice shall be
864
+ included in all copies or substantial portions of the Software.
865
+
866
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
867
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
868
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
869
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
870
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
871
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
872
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.