Giter Club home page Giter Club logo

rails's Introduction

Translation.io client for Ruby on Rails

Software License Build Status Test Coverage Gem Version Downloads

Add this gem to localize your Ruby on Rails application.

Use the official Rails syntax (with YAML files) or use the GetText syntax.

Write only the source text, and keep it synchronized with your translators on Translation.io.

Translation.io interface

Technical Demo (2.5min)

Need help? [email protected]

Table of contents

Translation syntaxes

I18n (YAML)

The default Rails Internationalization API.

# Regular
t('inbox.title')

# Pluralization
t('inbox.message', count: n)

# Interpolation
t('inbox.hello', name: @user.name)

With the source YAML file:

en:
  inbox:
    title:   'Title to be translated'
    message:
      zero:  'no messages'
      one:   'one message'
      other: '%{count} messages'
    hello:   'Hello %{name}'

You can keep your source YAML file automatically updated using i18n-tasks.

GetText

This gem adds the GetText support to Rails. We strongly suggest that you use GetText to translate your application since it allows an easier and more complete syntax.

Also, you won't need to create and manage any YAML file since your code will be automatically scanned for any string to translate.

# Regular
_("Text to be translated")

# Pluralization
n_("Singular text", "Plural text", number)

# Regular with context
p_("context", "Text to be translated")

# Pluralization with context
np_("context", "Singular text", "Plural text", number)

# Interpolations
_('%{city1} is bigger than %{city2}') % { city1: "NYC", city2: "BXL" }

More information about GetText syntax here.

Installation

  1. Add the gem to your project's Gemfile:
gem 'translation'
  1. Create a new translation project from the UI.
  2. Copy the initializer into your Rails app (config/initializers/translation.rb)

The initializer looks like this:

TranslationIO.configure do |config|
  config.api_key        = 'abcdefghijklmnopqrstuvwxyz012345'
  config.source_locale  = 'en'
  config.target_locales = ['fr', 'nl', 'de', 'es']
end
  1. Initialize your project and push existing translations to Translation.io with:
$ bundle exec rake translation:init

If you later need to add/remove target languages, please read our documentation about that.

Usage

Sync

To send new translatable keys/strings and get new translations from Translation.io, simply run:

$ bundle exec rake translation:sync

Sync and Show Purgeable

If you need to find out what are the unused keys/strings from Translation.io, using the current branch as reference:

$ bundle exec rake translation:sync_and_show_purgeable

As the name says, this operation will also perform a sync at the same time.

Sync and Purge

If you need to remove unused keys/strings from Translation.io, using the current branch as reference:

$ bundle exec rake translation:sync_and_purge

As the name says, this operation will also perform a sync at the same time.

Warning: all keys that are not present in the current branch will be permanently deleted from Translation.io.

Manage Languages

Add or Remove Language

You can add or remove a language by updating config.target_locales = [] in your config/initializers/translation.rb file, and executing rake translation:sync.

If you want to add a new language with existing translations (ex. if you already have a translated YAML file in your project), you will need to create a new project on Translation.io and run rake translation:init for them to appear.

Edit Language

To edit existing languages while keeping their translations (e.g. changing from en to en-US).

  1. Create a new project on Translation.io with the correct languages.
  2. Adapt config/initializers/translation.rb (new API key and languages)
  3. Adapt language names and root keys of the YAML files in your project (optional: adapt GetText directories and .po headers)
  4. Execute rake translation:init and check that everything went fine.
  5. Invite your collaborators in the new project.
  6. Remove the old project.

Since you created a new project, the translation history and tags will unfortunately be lost.

Custom Languages

You may want to add a custom language that is derived from an existing language. It's useful if you want to change some translations for another instance of the application or for a specific customer.

The structure of a custom language is : existing language code + "-" + custom text.

Examples: en-microsoft or fr-BE-custom.

Custom languages can be added like any other language and fallbacks work as expected. It means that if the en-microsoft.some_key is missing, then it will fallback to en.some_key. So you only need to translate keys that should be customized.

Note that fallback are chained, so fr-be-custom will fallback to fr-be that will itself fallback to fr.

Using GetText syntax, it will only fallback to the source language. So either you create a fallback mechanism by yourself or you avoid fallbacking by translating everything in Translation.io for that custom language.

Change the current locale

Globally

The easiest way to change the current locale is with set_locale.

class ApplicationController < ActionController::Base
  before_action :set_locale

  [...]
end

It will automatically set the locale extracted from the user's browser HTTP_ACCEPT_LANGUAGE value, and keep it in the session between requests.

Update the current locale by redirecting the user to https://yourdomain.com?locale=fr or even https://yourdomain.com/fr if you scoped your routes like this:

scope "/:locale", :constraints => { locale: /[a-z]{2}/ } do
  resources :pages
end

The set_locale code is here, feel free to override it with your own locale management.

Don't forget to define your available locales with I18n.available_locales.

More examples here: https://translation.io/blog/set-current-locale-in-your-rails-app

Locally

This command will change the locale for both I18n (YAML) and GetText:

I18n.locale = 'fr'

You can call it several times in the same page if you want to switch between languages.

More examples here: https://translation.io/blog/rails-i18n-with-locale

Advanced Configuration Options

The TranslationIO.configure block in config/initializers/translation.rb can take several optional configuration options.

Some options are described below but for an exhaustive list, please refer to config.rb.

Disable GetText

Sometimes, you only want to use YAML and don't want to be bothered by GetText at all. For these cases, you just have to add disable_gettext in the config file.

For example:

TranslationIO.configure do |config|
  ...
  config.disable_gettext = true
  ...
end

Ignored YAML keys

Sometimes you would like to ignore some YAML keys coming from gems or so. You can use the ignored_key_prefixes for that.

For example:

TranslationIO.configure do |config|
  ...
  config.ignored_key_prefixes = [
    'number.human.',
    'admin.',
    'errors.messages.',
    'activerecord.errors.messages.',
    'will_paginate.',
    'helpers.page_entries_info.',
    'views.pagination.',
    'enumerize.visibility.'
  ]
  ...
end

Source file formats (for GetText)

If you are using GetText and you want to manage other file formats than:

  • rb, erb, ruby and rabl for Ruby.
  • haml and mjmlhaml for HAML.
  • slim and mjmlslim for SLIM.

Just add them in your configuration file like this:

TranslationIO.configure do |config|
  ...
  config.source_formats      << 'rb2'
  config.haml_source_formats << 'haml2'
  config.slim_source_formats << 'slim2'
  ...
end

Custom localization key prefixes

Rails YAML files contain not only translation strings but also localization values (integers, arrays, booleans) in the same place and that's bad. For example: date formats, number separators, default currency or measure units, etc.

A translator is supposed to translate, not localize. That's not his role to choose how you want your dates or numbers to be displayed, right? Moreover, this special keys often contain special constructions (e.g., with percent signs or spaces) that he might break.

We think localization is part of the configuration of the app and it should not reach the translator UI at all. That's why these localization keys are detected and separated on a dedicated YAML file with Translation.io.

We automatically treat known localization keys, but if you would like to add some more, use the localization_key_prefixes option.

For example:

TranslationIO.configure do |config|
  ...
  config.localization_key_prefixes = ['my_gem.date.formats']
  ...
end

Paths where locales are stored (not recommended)

You can specify where your GetText and YAML files are on disk:

TranslationIO.configure do |config|
  ...
  config.locales_path      = 'some/path' # defaults to config/locales/gettext
  config.yaml_locales_path = 'some/path' # defaults to config/locales
  ...
end

Pure Ruby (without Rails)

This gem was created specifically for Rails, but you can also use it in a pure Ruby project by making some arrangements:

  require 'rubygems'
  require 'active_support/all'
  require 'yaml'

  class FakeConfig
    def after_initialize
    end
    def development?
      false
    end
  end

  module Rails
    class Railtie
      def self.rake_tasks
        yield
      end

      def self.initializer(*args)
      end

      def self.config
        ::FakeConfig.new
      end
    end

    def self.env
      ::FakeConfig.new
    end
  end

  task :environment do
  end

  require 'translation'

  I18n.load_path += Dir[File.join('i18n', '**', '*.{yml,yaml}')]

  # Put your configuration here:
  TranslationIO.configure do |config|
    config.yaml_locales_path = 'i18n'
    config.api_key           = ''
    config.source_locale     = 'en'
    config.target_locales    = ['nl', 'de']
    config.metadata_path     = 'i18n/.translation_io'
  end

(Thanks @kubaw for this snippet!)

Testing

To run the specs:

$ bundle exec rspec

Contributing

Please read the CONTRIBUTING file.

List of clients for Translation.io

These implementations were usually started by contributors for their own projects. Some of them are officially supported by Translation.io and some are not yet supported. However, they are quite well documented.

Thanks a lot to these contributors for their hard work!

Ruby on Rails (Ruby)

Officially Supported on https://translation.io/rails

Credits: @aurels, @michaelhoste

Laravel (PHP)

Officially Supported on https://translation.io/laravel

Credits: @armandsar, @michaelhoste

React and React-Intl (JavaScript)

Credits: @deecewan

Others

If you want to create a new client for your favorite language or framework, feel free to reach us on [email protected] and we'll assist you with the workflow logic and send you API docs.

License

The translation gem in released under MIT license by Aurélien Malisart and Michaël Hoste (see LICENSE file).

(c) https://translation.io / [email protected]

rails's People

Contributors

michaelhoste avatar ghiculescu avatar dombo avatar vddgil avatar

Stargazers

Aldis Berjoza avatar

Watchers

 avatar

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.