Code Monkey home page Code Monkey logo

i18n-js's Introduction

i18n.js

Export i18n translations to JSON.
A perfect fit if you want to export translations to JavaScript.

Oh, you don't use Ruby? No problem! You can still use i18n-js
and the companion JavaScript package.

Tests Gem Gem MIT License

Installation

gem install i18n-js

Or add the following line to your project's Gemfile:

gem "i18n-js"

Create a default configuration file in ./config/i18n.yml

i18n init

Usage

About patterns:

  • Patterns can use * as a wildcard and can appear more than once.
    • * will include everything
    • *.messages.*
  • Patterns starting with ! are excluded.
    • !*.activerecord.* will exclude all ActiveRecord translations.
  • You can use groups:
    • {pt-BR,en}.js.* will include only pt-BR and en translations, even if more languages are available.

Note:

Patterns use glob, so check it out for the most up-to-date documentation about what's available.

The config file:

---
translations:
  - file: app/frontend/locales/en.json
    patterns:
      - "*"
      - "!*.activerecord"
      - "!*.errors"
      - "!*.number.nth"

  - file: app/frontend/locales/:locale.:digest.json
    patterns:
      - "*"

The output path can use the following placeholders:

  • :locale - the language that's being exported.
  • :digest - the MD5 hex digest of the exported file.

The example above could generate a file named app/frontend/locales/en.7bdc958e33231eafb96b81e3d108eff3.json.

The config file is processed as erb, so you can have dynamic content on it if you want. The following example shows how to use groups from a variable.

---
<% group = "{en,pt}" %>

translations:
  - file: app/frontend/translations.json
    patterns:
      - "<%= group %>.*"
      - "!<%= group %>.activerecord"
      - "!<%= group %>.errors"
      - "!<%= group %>.number.nth"

Exporting locale.yml to locale.json

Your i18n yaml file can be exported to JSON using the Ruby API or the command line utility. Examples of both approaches are provided below:

The Ruby API:

require "i18n-js"

# The following call performs the same task as the CLI `i18n export` command
I18nJS.call(config_file: "config/i18n.yml")

# You can provide the config directly using the following
config = {
  "translations"=>[
    {"file"=>"app/javascript/locales/:locale.json", "patterns"=>["*"]}
  ]
}

I18nJS.call(config: config)
#=> ["app/javascript/locales/de.json", "app/javascript/locales/en.json"]

The CLI API:

$ i18n --help
Usage: i18n COMMAND FLAGS

Commands:

- init: Initialize a project
- export: Export translations as JSON files
- version: Show package version
- plugins: List plugins that will be activated
- lint:translations: Check for missing translations
- lint:scripts: Lint files using TypeScript

Run `i18n COMMAND --help` for more information on specific commands.

By default, i18n will use config/i18n.yml and config/environment.rb as the configuration files. If you don't have these files, then you'll need to specify both --config and --require.

Plugins

Built-in plugins:

embed_fallback_translations:

Embed fallback translations inferred from the default locale. This can be useful in cases where you have multiple large translation files and don't want to load the default locale together with the target locale.

To use it, add the following to your configuration file:

---
embed_fallback_translations:
  enabled: true
export_files:

By default, i18n-js will export only JSON files out of your translations. This plugin allows exporting other file formats. To use it, add the following to your configuration file:

---
export_files:
  enabled: true
  files:
    - template: path/to/template.erb
      output: "%{dir}/%{base_name}.ts"

You can export multiple files by defining more entries.

The output name can use the following placeholders:

  • %{dir}: the directory where the translation file is.
  • %{name}: file name with extension.
  • %{base_name}: file name without extension.
  • %{digest}: MD5 hexdigest from the generated file.

The template file must be a valid eRB template. You can execute arbitrary Ruby code, so be careful. An example of how you can generate a file can be seen below:

/* eslint-disable */
<%= banner %>

import { i18n } from "config/i18n";

i18n.store(<%= JSON.pretty_generate(translations) %>);

This template is loading the instance from config/i18n and storing the translations that have been loaded. The banner(comment: "// ", include_time: true) method is built-in. The generated file will look something like this:

/* eslint-disable */
// File generated by i18n-js on 2022-12-10 15:37:00 +0000

import { i18n } from "config/i18n";

i18n.store({
  en: {
    "bunny rabbit adventure": "bunny rabbit adventure",
    "hello sunshine!": "hello sunshine!",
    "time for bed!": "time for bed!",
  },
  es: {
    "bunny rabbit adventure": "conejito conejo aventura",
    bye: "adios",
    "time for bed!": "hora de acostarse!",
  },
  pt: {
    "bunny rabbit adventure": "a aventura da coelhinha",
    bye: "tchau",
    "time for bed!": "hora de dormir!",
  },
});

Plugin API

You can transform the exported translations by adding plugins. A plugin must inherit from I18nJS::Plugin and can have 4 class methods (they're all optional and will default to a noop implementation). For real examples, see lib/i18n-js/embed_fallback_translations_plugin.rb and lib/i18n-js/export_files_plugin.rb

# frozen_string_literal: true

module I18nJS
  class SamplePlugin < I18nJS::Plugin
    # This method is responsible for transforming the translations. The
    # translations you'll receive may be already be filtered by other plugins
    # and by the default filtering itself. If you need to access the original
    # translations, use `I18nJS.translations`.
    def transform(translations:)
      # transform `translations` here…

      translations
    end

    # In case your plugin accepts configuration, this is where you must validate
    # the configuration, making sure only valid keys and type is provided.
    # If the configuration contains invalid data, then you must raise an
    # exception using something like
    # `raise I18nJS::Schema::InvalidError, error_message`.
    #
    # Notice the validation will only happen when the plugin configuration is
    # set (i.e. the configuration contains your config key).
    def validate_schema
      # validate plugin schema here…
    end

    # This method must set up the basic plugin configuration, like adding the
    # config's root key in case your plugin accepts configuration (defined via
    # the config file).
    #
    # If you don't add this key, the linter will prevent non-default keys from
    # being added to the configuration file.
    def setup
      # If you plugin has configuration, uncomment the line below
      # I18nJS::Schema.root_keys << config_key
    end

    # This method is called whenever `I18nJS.call(**kwargs)` finishes exporting
    # JSON files based on your configuration.
    #
    # You can use it to further process exported files, or generate new files
    # based on the translations that have been exported.
    def after_export(files:)
      # process exported files here…
    end
  end
end

The class I18nJS::Plugin implements some helper methods that you can use:

  • I18nJS::Plugin#config_key: the configuration key that was inferred out of your plugin's class name.
  • I18nJS::Plugin#config: the plugin configuration.
  • I18nJS::Plugin#enabled?: whether the plugin is enabled or not based on the plugin's configuration.

To distribute this plugin, you need to create a gem package that matches the pattern i18n-js/*_plugin.rb. You can test whether your plugin will be found by installing your gem, opening a iRB session and running Gem.find_files("i18n-js/*_plugin.rb"). If your plugin is not listed, then you need to double check your gem load path and see why the file is not being loaded.

Listing missing translations

To list missing and extraneous translations, you can use i18n lint:translations. This command will load your translations similarly to how i18n export does, but will output the list of keys that don't have a matching translation against the default locale. Here's an example:

$ i18n lint:translations
=> Config file: "./config/i18n.yml"
=> Require file: "./config/environment.rb"
=> Check "./config/i18n.yml" for ignored keys.
=> en: 232 translations
=> pt-BR: 5 missing, 1 extraneous, 1 ignored
   - pt-BR.actors.github.metrics (missing)
   - pt-BR.actors.github.metrics_hint (missing)
   - pt-BR.actors.github.repo_metrics (missing)
   - pt-BR.actors.github.repository (missing)
   - pt-BR.actors.github.user_metrics (missing)
   - pt-BR.github.repository (extraneous)

This command will exit with status 1 whenever there are missing translations. This way you can use it as a CI linting tool.

You can ignore keys by adding a list to the config file:

---
translations:
  - file: app/frontend/locales/en.json
    patterns:
      - "*"
      - "!*.activerecord"
      - "!*.errors"
      - "!*.number.nth"

  - file: app/frontend/locales/:locale.:digest.json
    patterns:
      - "*"

lint_translations:
  ignore:
    - en.mailer.login.subject
    - en.mailer.login.body

Note:

In order to avoid mistakenly ignoring keys, this configuration option only accepts the full translation scope, rather than accepting a pattern like pt.ignored.scope.*.

Linting your JavaScript/TypeScript files

To lint your script files and check for missing translations (which can signal that you're either using wrong scopes or forgot to add the translation), use i18n lint:scripts. This command will parse your JavaScript/TypeScript files and extract all scopes being used. This command requires a Node.js runtime. You can either specify one via --node-path, or let the plugin infer a binary from your $PATH.

The comparison will be made against the export JSON files, which means it'll consider transformations performed by plugins (e.g. the output files may be affected by embed_fallback_translations plugin).

The translations that will be extract must be called as one of the following ways:

  • i18n.t(scope, options)
  • i18n.translate(scope, options)
  • t(scope, options)

Notice that only literal strings can be used, as in i18n.t("message"). If you're using dynamic scoping through variables (e.g. const scope = "message"; i18n.t(scope)), they will be skipped.

$ i18n lint:scripts
=> Config file: "./config/i18n.yml"
=> Require file: "./config/environment.rb"
=> Node: "/Users/fnando/.asdf/shims/node"
=> Available locales: [:en, :es, :pt]
=> Patterns: ["!(node_modules)/**/*.js", "!(node_modules)/**/*.ts", "!(node_modules)/**/*.jsx", "!(node_modules)/**/*.tsx"]
=> 9 translations, 11 missing, 4 ignored
   - test/scripts/lint/file.js:1:1: en.js.missing
   - test/scripts/lint/file.js:1:1: es.js.missing
   - test/scripts/lint/file.js:1:1: pt.js.missing
   - test/scripts/lint/file.js:2:8: en.base.js.missing
   - test/scripts/lint/file.js:2:8: es.base.js.missing
   - test/scripts/lint/file.js:2:8: pt.base.js.missing
   - test/scripts/lint/file.js:4:8: en.js.missing
   - test/scripts/lint/file.js:4:8: es.js.missing
   - test/scripts/lint/file.js:4:8: pt.js.missing
   - test/scripts/lint/file.js:6:1: en.another_ignore_scope
   - test/scripts/lint/file.js:6:1: es.another_ignore_scope

This command will list all locales and their missing translations. To avoid listing a particular translation, you can set lint_scripts.ignore or lint_translations.ignore in your config file.

---
translations:
  - file: app/frontend/translations.json
    patterns:
      - "*"

lint_scripts:
  ignore:
    - ignore_scope # will ignore this scope on all languages
    - pt.another_ignore_scope # will ignore this scope only on `pt`

You can also set the patterns that will be looked up. By default, it scans all JavaScript and TypeScript files that don't live on node_modules.

---
translations:
  - file: app/frontend/translations.json
    patterns:
      - "*"

lint_scripts:
  patterns:
    - "app/assets/**/*.ts"

Automatically export translations

Using watchman

Create a script at bin/i18n-watch.

#!/usr/bin/env bash

root=`pwd`

watchman watch-del "$root"
watchman watch-project "$root"
watchman trigger-del "$root" i18n

watchman -j <<-JSON
[
  "trigger",
  "$root",
  {
    "name": "i18n",
    "expression": [
      "anyof",
      ["match", "config/locales/**/*.yml", "wholename"],
      ["match", "config/i18n.yml", "wholename"]
    ],
    "command": ["i18n", "export"]
  }
]
JSON

# If you're running this through Foreman,
# then uncomment the following lines:
# while true; do
#   sleep 1
# done

Make it executable with chmod +x bin/i18n-watch. To watch for changes, run ./bin/i18n-watch. If you're using Foreman, make sure you uncommented the lines that keep the process running (while..), and add something like the following line to your Procfile:

i18n: ./bin/i18n-watch

Using guard

Install guard and guard-compat. Then create a Guardfile with the following configuration:

guard(:"i18n-js",
      run_on_start: true,
      config_file: "./config/i18n.yml",
      require_file: "./config/environment.rb") do
  watch(%r{^(app|config)/locales/.+\.(yml|po)$})
  watch(%r{^config/i18n.yml$})
  watch("Gemfile")
end

If your files are located in a different path, remember to configure file paths accordingly.

Now you can run guard start -i.

Using listen

Create a file under config/initializers/i18n.rb with the following content:

Rails.application.config.after_initialize do
  require "i18n-js/listen"
  I18nJS.listen
end

The code above will watch for changes based on config/i18n.yml and config/locales. You can customize these options:

  • config_file - i18n-js configuration file
  • locales_dir - one or multiple directories to watch for locales changes
  • options - passed directly to listen
  • run_on_start - export files on start. Defaults to true. When disabled, files will be exported only when there are file changes.

Example:

I18nJS.listen(
  config_file: "config/i18n.yml",
  locales_dir: ["config/locales", "app/views"],
  options: {only: %r{.yml$}},
  run_on_start: false
)

Integrating with your frontend

You're done exporting files, now what? Well, go to i18n to discover how to use the NPM package that loads all the exported translation.

FAQ

I'm running v3. Is there a migration plan?

There's a document outlining some of the things you need to do to migrate from v3 to v4. It may not be as complete as we'd like it to be, so let us know if you face any issues during the migration that is not outlined in that document.

How can I export translations without having a database around?

Some people may have a build process using something like Docker that don't necessarily have a database available. In this case, you may define your own loading file by using something like i18n export --require ./config/i18n_export.rb, where i18n_export.rb may look like this:

# frozen_string_literal: true

require "bundler/setup"
require "rails"
require "active_support/railtie"
require "action_view/railtie"

I18n.load_path += Dir["./config/locales/**/*.yml"]

Note:

You may not need to load the ActiveSupport and ActionView lines, or you may need to add additional requires for other libs. With this approach you have full control on what's going to be loaded.

Maintainer

Contributors

Contributing

For more details about how to contribute, please read https://github.com/fnando/i18n-js/blob/main/CONTRIBUTING.md.

License

The gem is available as open source under the terms of the MIT License. A copy of the license can be found at https://github.com/fnando/i18n-js/blob/main/LICENSE.md.

Code of Conduct

Everyone interacting in the i18n-js project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

i18n-js's People

Contributors

dependabot[bot] avatar fnando avatar marky1124 avatar mishina2228 avatar oleksii-leonov avatar olleolleolle avatar runephilosof-karnovgroup avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

i18n-js's Issues

Timezone is not respected

From the Facebook and the Twitter API I get timestamps in different formats. I want to display them in a german locale with I18n.l(), but the displayed time is not correct (the Facebook timestamp is 2 hours behind). I digged a little into the code and found that the I18n.parseDate() method behaves (IMHO) strange. It doesn't respect the timezone information (other than 'Z'), whereas the Date.parse() fallback handles it correctly.

I18n.locale = "de";

// From Facebook API
I18n.parseDate('2011-07-20T12:51:55+0000');
Wed Jul 20 2011 12:51:55 GMT+0200 (CEST)

I18n.parseDate('2011-07-20T12:51:55Z');
Wed Jul 20 2011 14:51:55 GMT+0200 (CEST)

// From Twitter API
I18n.parseDate("Wed Jul 20 13:03:39 +0000 2011");
Wed Jul 20 2011 15:03:39 GMT+0200 (CEST)

Is there a reason to have an own parseDate implementation?

Ready as gem

That's it for the gem part : http://github.com/ZenCocoon/i18n-js/tree/gem

Just make sure the descriptions, requirement suits your expectation in the Rakefie.

If you do some update there, don't forget to push your changes to the gemspec by doing :

rake gemspec

Once you happy with the release, check http://github.com/technicalpickles/jeweler at "Releasing to Gemcutter" to push it to gemcutter ;-)

Check jeweler "Versioning" to help you pushing version updates before each release, pretty simple thought ;-)

Let me know if something block ;-)

Problem with Rails 3.1 and test environment

I'm upgrading an existing Rails 3.0 app to Rails 3.1 (with i18n-js-1.1.0), but I have problems in test environment. The translations are not working, they result in [missing ... translation].

It makes no difference whether I run the cucumber tests or the server directly in the test environment.

auto_export: yes

translations:
  - file: "app/assets/javascripts/i18n/translations.js"

asset_pipeline: yes
[...]

//= require i18n
//= require i18n/translations
[...]
  • The auto_export flag works and creates the translations.js file if it doesn't exist
  • RAILS_ENV=test rake i18n:js:export assets:precompile produces a applications.js where my translations are included, but the error still occurs.

Is this a configuration issue or how is it supposed to work in test/production environment?

cyrillic export

What about export with gem ya2yaml for js
because now it is not very redable

I18n.translations = {"ru":{"widget":{"global":{"all":"\u0412\u0441\u0435:","save":"\u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c",

exporting on app boot is problematic

Often in a production deployment, public assets are in a different location than in development. Sometimes not even under Rails.root (this is the case for my project). Sometimes not even on the same physical machine. In such cases, the export triggered by init.rb fails.

I'm not sure exactly how, but exporting on boot needs to be configurable, maybe even off by default. I've worked around it by removing the export in init.rb and having my pre-deploy script run an export.

I18n.toNumber inappropriately adds a delimiter to negative numbers 3 digits or less

When toNumber is passed a negative number it can result in output like this: -,123. The delimiter should not be present. The problem appears to be that the n array ends up with the negative character as the first element. Here is a possible fix that is work for me. It would start at line 255 in i18n.js:

var negative = null;

if (number.charAt(0) == '-') {
negative = number.substr(0, 1);
number = number.substr(1, number.length);
}

while (number.length > 0) {
n.unshift(number.substr(Math.max(0, number.length - 3), 3));
number = number.substr(0, number.length -3);
}

var formattedNumber = n.join(options["delimiter"]);

if (negative != null) {
formattedNumber = negative + formattedNumber;
}

I'm not sure if the proper etiquette is to fork and keeping going or to let the author know. I've opted for the later but, feel free to tell me to buzz off and do the former.

rake i18n:js:update failing with redirection forbidden error (open-uri)

Hi Nando,

Thanks for releasing i18n-js, it's really cool!

I stumbled across a small bug today running (padrino) rake i18n:js:update:

RuntimeError: redirection forbidden: http://github.com/fnando/i18n-js/raw/master/lib/i18n.js -> https://github.com/fnando/i18n-   js/raw/master/lib/i18n.js

Looks like replacing line 80 on i18n-js.rb with

open('https://raw.github.com/fnando/i18n-js/master/lib/i18n-js.rb').read

should do the trick, looks like the URL for accessing raw source files on github has changed.

Cheers!

console.debug in I18n.js

I think you should remove console.debug(placeholder) and console.debug(name) from the i18n.js file.
I got an error message on IE7.

NoMethodError: undefined method `assets' during set up with JRuby/Rails 3.0.10

When attempting to run rake i18n:js:setup on JRuby 1.6.4, the following error is occurring:

C:\Temp\foobar>jruby -S rake i18n:js:setup --trace
** Invoke i18n:js:setup (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
undefined method `assets' for #<Rails::Application::Configuration:0xdd67cf>
org/jruby/RubyKernel.java:238:in `method_missing'
C:/skunkworx/jruby/jruby-1.6.4/lib/ruby/gems/1.8/gems/railties-3.0.10/lib/rails/railtie/configuration.rb:77:in `method_missing'  
C:/skunkworx/jruby/jruby-1.6.4/lib/ruby/gems/1.8/gems/i18n-js-2.1.0/lib/i18n-js/railtie.rb:9:in `Railtie'
....

I believe that this error is stemming from an assumption that the gem is being used with Rails 3.1.
Please see line 9 in lib/i18n-js/railtie.rb:

app.config.middleware.use(Middleware) if Rails.env.development? && !Rails.configuration.assets.enabled

... where Rails.configuration.assets is present in Rails 3.1, but not present in versions lower than 3.1.

Here are my ruby and gem details:

C:\Temp\foobar>jruby -v
jruby 1.6.4 (ruby-1.8.7-p330) (2011-08-23 17ea768) (Java HotSpot(TM) Client VM 1.6.0_13) [Windows XP-x86-java]

C:\Temp\foobar>jruby -S gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 1.5.1
  - RUBY VERSION: 1.8.7 (2011-08-23 patchlevel 330) [java]
  - INSTALLATION DIRECTORY: C:/skunkworx/jruby/jruby-1.6.4/lib/ruby/gems/1.8
  - RUBY EXECUTABLE: C:/skunkworx/jruby/jruby-1.6.4/bin/jruby.exe
  - EXECUTABLE DIRECTORY: C:/skunkworx/jruby/jruby-1.6.4/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-java-1.6
  - GEM PATHS:
     - C:/skunkworx/jruby/jruby-1.6.4/lib/ruby/gems/1.8
     - C:/Documents and Settings/6008895/.gem/jruby/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - "install" => "--no-rdoc --no-ri --env-shebang"
     - "update" => "--no-rdoc --no-ri --env-shebang"
  - REMOTE SOURCES:
     - http://rubygems.org/

C:\Temp\foobar>jruby -S gem li

*** LOCAL GEMS ***

abstract (1.0.0)
actionmailer (3.0.10)
actionpack (3.0.10)
activemodel (3.0.10)
activerecord (3.0.10)
activeresource (3.0.10)
activesupport (3.0.10)
arel (2.0.10)
bouncy-castle-java (1.5.0146.1)
builder (2.1.2)
bundler (1.0.21)
erubis (2.6.6)
i18n (0.6.0, 0.5.0)
i18n-js (2.1.0)
jruby-openssl (0.7.4)
json (1.6.1 java)
mail (2.2.19)
mime-types (1.16)
polyglot (0.3.2)
rack (1.2.4)
rack-mount (0.6.14)
rack-test (0.5.7)
rails (3.0.10)
railties (3.0.10)
rake (0.9.2, 0.8.7)
rdoc (3.11)
sources (0.0.1)
thor (0.14.6)
treetop (1.4.10)
tzinfo (0.3.30)

Translations turn "yes" and "no" into "true" and "false"

Whenever the lowercase word "yes" appears in the Rails language yaml (e.g. en.yml), and rake i18n:export is run, the resulting javascript translation will replace the word with "true". The same applies for "no" becoming false.

en:
    yes: yes
    no: no
    other: Yes

becomes

{"en":{"true":"true","false":"false","other":"Yes"}

method missing "assets"

I'm trying to run i18n-js 2.1.0 (last version) with Rails 3.0.9 but I'd this error:

/Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/railtie/configuration.rb:77:in `method_missing': undefined method `assets' for #<Rails::Application::Configuration:0x000001033b60d8> (NoMethodError)
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/i18n-js-2.1.0/lib/i18n-js/railtie.rb:9:in `block in <class:Railtie>'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/initializable.rb:25:in `instance_exec'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/initializable.rb:25:in `run'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/initializable.rb:50:in `block in run_initializers'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/initializable.rb:49:in `each'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/initializable.rb:49:in `run_initializers'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/application.rb:134:in `initialize!'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/application.rb:77:in `method_missing'
    from /Users/estevao/Projects/Ledface/config/environment.rb:7:in `<top (required)>'
    from /Users/estevao/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/estevao/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/estevao/Projects/Ledface/config.ru:3:in `block in <main>'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.2.4/lib/rack/builder.rb:46:in `instance_eval'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.2.4/lib/rack/builder.rb:46:in `initialize'
    from /Users/estevao/Projects/Ledface/config.ru:1:in `new'
    from /Users/estevao/Projects/Ledface/config.ru:1:in `<main>'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/lib/rack/adapter/loader.rb:36:in `eval'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/lib/rack/adapter/loader.rb:36:in `load'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/lib/rack/adapter/loader.rb:45:in `for'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/lib/thin/controllers/controller.rb:169:in `load_adapter'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/lib/thin/controllers/controller.rb:73:in `start'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/lib/thin/runner.rb:185:in `run_command'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/lib/thin/runner.rb:151:in `run!'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/gems/thin-1.2.11/bin/thin:6:in `<top (required)>'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/bin/thin:19:in `load'
    from /Users/estevao/.rvm/gems/ruby-1.9.2-p180/bin/thin:19:in `<main>'

What could I do about it?
And btw thanks, awesome gem! :)

New release coming soon

Hi there everyone!

I just rewrote the I18n.js. I was trying to apply some PRs and notice the whole codebase just got messy. Both the Ruby and JavaScript part. So here's what I did:

  • Removed some functionalities like rake tasks to generate config files.
  • Keep the JavaScript API on the most part but some things may be broken, specially the fallback and pluralization rules. If you' re not using those, you're good.
  • Tried to simplify the asset pipeline support. Yeah, that was a complex code, so please test it.
  • I'm running tests in both browser and Node.js, so I guess you can use it.

I'm planning to release this thing next week, so if you're using I18n.js, please give it some love and test it. The new codebase lives on https://github.com/fnando/i18n-js/tree/rewrite. You can easily test it by following the README's install instruction and adding the gem as a Git repository.

gem "i18n-js", :git => "git://github.com/fnando/i18n-js.git", :branch => "rewrite"

Thanks! ;)

uninitialized constant SimplesIdeias

I've installed plugin with:
script/plugin install git://github.com/fnando/i18n-js.git

And executed rake task:
rake i18n:setup

And I've got an error:
uninitialized constant SimplesIdeias

uninitialized constant Syck::Syck

Hi Nando!

It seems that i18n-js has some problems with latest rubygems :(
I added it to my Gemfile and got this error:

bundle install
Invalid gemspec in [/Users/user/.rvm/gems/ruby-1.9.2-p180@chk2/specifications/i18n-js-1.1.0.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000105255d90> 0.8.7"]
Invalid gemspec in [/Users/user/.rvm/gems/ruby-1.9.2-p180@chk2/specifications/i18n-js-1.1.0.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000105255d90> 0.8.7"]
Fetching source index for http://rubygems.org/
/Users/user/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:289:in `load': uninitialized constant Syck::Syck (NameError)

My rubygems version:

gem -v
1.8.10

How can I fix this problem?

support '-' strftime conversion specifier

GNU C library supports a ton of standard and not-so-standard strftime options.

http://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html

Not sure how many of those we want to get to. The one of interest to me is the '-' conversion specifier, which indicates no padding for numbers. I want my en datetime format to be "%-m/%-d/%y %-I:%M %p". For example, Ruby 1.9:

$ ruby1.9 -e 'puts Time.now.strftime("%-m/%-d/%y %-I:%M %p")'
2/26/10 3:07 PM

BTW, just updated to the latest -- the new number formatting stuff rocks.

README is unclear about how to include the generated translation files

The gem allows a variety of ways to generate and organize the files with translations. There is also the public/javascripts/i18n.js file, that is required by all the generated scripts. The README does not specify if there is a recommended way to include these in HTML files and ERB templates.

Is there a recommended approach?

Fallback doesn't work for non existent locale

I18n.fallbacks = true;
I18n.locale = 'qq'; //not existent locale
I18n.t('some.key'); // => missing translation, though translation for some.key exists in default locale
// workaround:
I18n.translations.qq = {}
I18n.t('some.key'); // => now it works as expected

Missing options on function toCurrency

The standard i18n option "strip_insignificant_zeros" is not implemented and by default the insignificant zeros are not striped.
The addition will be really appreciated, thanks

undefined method `mtime' for nil:NilClass

We got this error in Rails 3.1.3 with the asset pipeline enabled as soon as we include the

//= require i18n/translations

line in the application.js file. It may be related with a bug in sprockets we found:

We worked around the problem by running rake i18n:js:setup. This created the config file and everything seems to work now.

Cant generate js

➜  maxhost git:(master) ✗ rake i18n:export --trace
(in /Users/ernest/Projekty/maxhost)
** Invoke i18n:export (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute i18n:export
rake aborted!
stack level too deep
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/i18n-js.rb:66:in `to_json'
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/i18n-js.rb:66:in `save'
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/i18n-js.rb:63:in `open'
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/i18n-js.rb:63:in `save'
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/i18n-js.rb:22:in `export!'
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/i18n-js.rb:18:in `each'
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/i18n-js.rb:18:in `export!'
/Users/ernest/Projekty/maxhost/vendor/plugins/i18n-js/lib/tasks/i18n-js_tasks.rake:9
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/opt/ruby18/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/opt/ruby18/lib/ruby/gems/1.8/gems/rake-0.8.7/bin/rake:31
/opt/ruby18/bin/rake:19:in `l

when rake i18n:export

readme questions

"You should change the path in i18n.js.yml to app/assets/javascripts/i18n to make full use of the asset pipeline."

  1. typo: i18n-js.yml (not i18n.js.yml), correct?
  2. I open that file and don't see where I should "change the path"?

Next add the following lines to your application.js to make the javascripts and translations available to your app:
3. To confirm, I'm supposed to add these two lines to "public/javascripts/application.js"?

//= require i18n
//= require i18n/translations

need better control over precision in number localization

Rails has two methods for formatting numbers: number_with_delimiter and number_with_precision. I18n.js has only localize("number")/toNumber, which is closest to number_with_precision in result. But typically when formatting an integer you do not wish to add any precision nor a units separator, only add thousands delimiters. I.e., there should be a way to get number_with_delimiter-like behavior.

Usage w/ asset pipeline + Heroku possible?

Heroku requires

config.assets.initialize_on_precompile = false

On the other hand i18n-js requires this to be true. Any idea on how to use i18n-js when deploying to Heroku except manually exporting translations before each push...?

broken capability with Rails 3.1

RuntimeError Cannot precompile i18n-js translations unless environment is initialized. Please set config.assets.initialize_on_precompile to true. (in /Users/Kir/.rvm/gems/ruby-1.9.2-p290@ools/gems/i18n-js-2.1.2/vendor/assets/javascripts/i18n/translations.js.erb)

But config.assets.initialize_on_precompile = true is already set in application.rb.
Rails version Rails 3.1.0.

switch to different i18n backend throws error

Hey,
if i change my i18n backend to

 # config/initializers/i18n_backend.rb
 TRANSLATION_STORE = Redis.new
 I18n.backend = I18n::Backend::Chain.new(I18n::Backend::KeyValue.new(TRANSLATION_STORE), I18n.backend)

it throws an

NoMethodError (undefined method `initialized?' for #<I18n::Backend::Chain:0x007fca09d6c920>):

error.

if i remove the i18n.js gem it works fine.... i dont have any more backtrace for debugging...

kalle

ps. nice gem by the way, love it !

Long delay on page load

After adding your gem in my rails 3.1 application each http url was taking 1s to load in development mode (and I mean each: css, js, html), I quickly looked at the source but could not figure why it was taking so long until I realized that th etranslation.js file was genrated on every request :s

Why not generate the file once for all and serves it using the asset pipeline (or copy it in app folder for older rails versions) ?

Using multiple i18n files not possible

I have a application-wide i18n file plus some controller-specific i18n files.
Now when I load both on a page, only the translations from the i18n file loaded last are available, the others are missing.

As a hack I included all application-wide translations in the controller-specific i18n file in i18n-js.yml thus loading the application-wide translations twice on those pages.

Am I doing something wrong in terms of configuration?
I suppose a reasonable solution would be not to set I18n.translations equal the following array of translations, but to add the array of translations to it thus making it possible to have multiple files in one page.

Translation file should be written only when changed

Right now translation file write's everytime when middleware called. It should somehow check before write (by md5 hash or similar), that locales haven't changed since the last file write.

If you don't have a time, please advice me how to do it better and I'll attach patch in some time later.

Add Configuration file management

Here we go: http://github.com/ZenCocoon/i18n-js/tree/config

Configuration files management with support for :

  • i18n.js library location customization
  • multiple translations files
  • translations files location customization
  • translations scoping using only keyword

only supports scopes like "*.admin.*.title" or even arrays like ["*.activerecord", "*.admin.*.title"]

The patch comes with test suits and updated documentation. Still make sure to review it anyway.

Hope that helps making i18n-js even better,

Sébastien Grosjean - ZenCocoon

messages.js missing a semicolon

Hi, first up: crackerjack plugin, I love it. (Using it on http://twerpscan.com/.)

I've found a tiny issue with the generated messages.js — it's missing a semicolon at the very end. The I18n.translations = … is a variable declaration and the line needs to be ended properly. A problem arises if you make messages.js a part of the javascript_include_tag call. In production mode, all JS is concatenated, and if messages.js wasn't the last entry in the list, it might "break" the generated all.js, i.e. some JS parsers are stumbling over the missing semicolon.

Split translations into files depending on the top-level key

Basically, have one file per locale. So this would generate

app/assets/javascripts/
  i18n/
    en.js
    pt-BR.js
    es.js

If I want to change locales without reloading the page, or I don't care about having multiple locales loaded at the same time, I can just:

//= require_tree ./i18n

If, however, I want to require only the current locale because to change locales I need to reload anyway, and want to save some space on the request size:

<%= javascript_include_tag :i18n, "i18n/#{I18n.current_locale}", :application %>

Any thoughts on this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.