Pluggable Ruby translation framework
This is the readme for version 1.x of Mobility. If you are using an earlier version (0.8.x or earlier), you probably want the readme on the 0-8 branch.
Mobility is a gem for storing and retrieving translations as attributes on a class. These translations could be the content of blog posts, captions on images, tags on bookmarks, or anything else you might want to store in different languages. For examples of what Mobility can do, see the Companies using Mobility section below.
Storage of translations is handled by customizable "backends" which encapsulate different storage strategies. The default way to store translations is to put them all in a set of two shared tables, but many alternatives are also supported, including translatable columns and model translation tables, as well as database-specific storage solutions such as json/jsonb and Hstore (for PostgreSQL).
Mobility is a cross-platform solution, currently supporting both ActiveRecord and Sequel ORM, with support for other platforms planned.
For a detailed introduction to Mobility, see Translating with Mobility. See also my talk at RubyConf 2018, Building Generic Software, where I explain the thinking behind Mobility's design.
If you're coming from Globalize, be sure to also read the Migrating from Globalize section of the wiki.
Add this line to your application's Gemfile:
gem 'mobility', '~> 1.3.2'Requirements:
To translate attributes on a model, extend Mobility, then call translates
passing in one or more attributes as well as a hash of options (see below).
If using Mobility in a Rails project, you can run the generator to create an
initializer and a migration to create shared translation tables for the
default KeyValue backend:
rails generate mobility:install(If you do not plan to use the default backend, you may want to use
the --without_tables option here to skip the migration generation.)
The generator will create an initializer file config/initializers/mobility.rb
which looks something like this:
Mobility.configure do
# PLUGINS
plugins do
backend :key_value
active_record
reader
writer
# ...
end
endEach method call inside the block passed to plugins declares a plugin, along
with an optional default. To use a different default backend, you can
change the default passed to the backend plugin, like this:
Mobility.configure do
# PLUGINS
plugins do
- backend :key_value
+ backend :tableSee other possible backends in the backends section.
You can also set defaults for backend-specific options. Below, we set the
default type option for the KeyValue backend to :string.
Mobility.configure do
# PLUGINS
plugins do
- backend :key_value
+ backend :key_value, type: :string
end
endWe will assume the configuration above in the examples that follow.
See Getting Started to get started translating your models.
Requirements:
When configuring Mobility, ensure that you include the sequel plugin:
plugins do
backend :key_value
- active_record
+ sequelYou can extend Mobility just like in ActiveRecord, or you can use the
mobility plugin, which does the same thing:
class Word "mobility"
word.meaning
#=> "(noun): quality of being changeable, adaptable or versatile"
word.save
word = Word.first
word.name
#=> "mobility"
word.meaning
#=> "(noun): quality of being changeable, adaptable or versatile"Presence methods are also supported:
word.name?
#=> true
word.name = nil
word.name?
#=> false
word.name = ""
word.name?
#=> falseWhat's different here is that the value of these attributes changes with the
value of I18n.locale:
I18n.locale = :ja
word.name
#=> nil
word.meaning
#=> nilThe name and meaning of this word are not defined in any locale except
English. Let's define them in Japanese and save the model:
word.name = "モビリティ"
word.meaning = "(名詞):動きやすさ、可動性"
word.name
#=> "モビリティ"
word.meaning
#=> "(名詞):動きやすさ、可動性"
word.saveNow our word has names and meanings in two different languages:
word = Word.first
I18n.locale = :en
word.name
#=> "mobility"
word.meaning
#=> "(noun): quality of being changeable, adaptable or versatile"
I18n.locale = :ja
word.name
#=> "モビリティ"
word.meaning
#=> "(名詞):動きやすさ、可動性"Internally, Mobility is mapping the values in different locales to storage locations, usually database columns. By default these values are stored as keys (attribute names) and values (attribute translations) on a set of translation tables, one for strings and one for text columns, but this can be easily changed and/or customized (see the Backends section below).
The easiest way to get or set a translation is to use the getter and setter
methods described above (word.name and word.name=), enabled by including
the reader and writer plugins.
You may also want to access the value of an attribute in a specific locale,
independent of the current value of I18n.locale (or Mobility.locale). There
are a few ways to do this.
The first way is to define locale-specific methods, one for each locale you
want to access directly on a given attribute. These are called "locale
accessors" in Mobility, and can be enabled by including the locale_accessors
plugin, with a default set of accessors:
plugins do
# ...
+ locale_accessors [:en, :ja]You can also override this default from translates in any model:
class Word "mobility"
word.name_ja
#=> "モビリティ"
word.name_en = "foo"
word.name
#=> "foo"Other locales, however, will not work:
word.name_ru
#=> NoMethodError: undefined method `name_ru' for #With no plugin option (or a default of true), Mobility generates methods for
all locales in I18n.available_locales at the time the model is first loaded.
An alternative to using the locale_accessors plugin is to use the
fallthrough_accessors plugin. This uses Ruby's
method_missing method
to implicitly define the same methods as above, but supporting any locale
without any method definitions. (Locale accessors and fallthrough locales can
be used together without conflict, with locale accessors taking precedence if
defined for a given locale.)
Ensure the plugin is enabled:
plugins do
# ...
+ fallthrough_accessors... then we can access any locale we want, without specifying them upfront:
word = Word.new
word.name_fr = "mobilité"
word.name_fr
#=> "mobilité"
word.name_ja = "モビリティ"
word.name_ja
#=> "モビリティ"(Note however that Mobility will complain if you have
I18n.enforce_available_locales set to true and you try accessing a locale
not present in I18n.available_locales; set it to false if you want to allow
any locale.)
Another way to fetch values in a locale is to pass the locale option to the
getter method, like this:
word.name(locale: :en)
#=> "mobility"
word.name(locale: :fr)
#=> "mobilité"Note that setting the locale this way will pass an option locale: true to the
backend and all plugins. Plugins may use this option to change their behavior
(passing the locale explicitly this way, for example, disables
fallbacks, see below for details).
You can also set the value of an attribute this way; however, since the
word.name = syntax does not accept any options, the only way to do this is to
use send (this is included mostly for consistency):
word.send(:name=, "mobiliteit", locale: :nl)
word.name_nl
#=> "mobiliteit"Yet another way to get and set translated attributes is to call read and
write on the storage backend, which can be accessed using the method
_backend. Without worrying too much about the details of
how this works for now, the syntax for doing this is simple:
word.name_backend.read(:en)
#=> "mobility"
word.name_backend.read(:nl)
#=> "mobiliteit"
word.name_backend.write(:en, "foo")
word.name_backend.read(:en)
#=> "foo"Internally, all methods for accessing translated attributes ultimately end up
reading and writing from the backend instance this way. (The write methods
do not call underlying backend's methods to persist the change. This is up to
the user, so e.g. with ActiveRecord you should call save write the changes to
the database).
Note that accessor methods are defined in an included module, so you can wrap reads or writes in custom logic:
class Post :en
Mobility.locale = :fr
Mobility.locale #=> :fr
I18n.locale #=> :enTo set the Mobility locale in a block, you can use Mobility.with_locale (like
I18n.with_locale):
Mobility.locale = :en
Mobility.with_locale(:ja) do
Mobility.locale #=> :ja
end
Mobility.locale #=> :enMobility uses RequestStore to reset these global variables after every request, so you don't need to worry about thread safety. If you're not using Rails, consult RequestStore's README for details on how to configure it for your use case.
Mobility offers basic support for translation fallbacks. First, enable the
fallbacks plugin:
plugins do
# ...
+ fallbacks
+ locale_accessorsFallbacks will require fallthrough_accessors to handle methods like
title_en, which are used to track changes. For performance reasons it's
generally best to also enable the locale_accessors plugin as shown above.
Now pass a hash with fallbacks for each locale as an option when defining translated attributes on a class:
class Word "モビリティ"
word.meaning
#=> "(名詞):動きやすさ、可動性"
Mobility.locale = :fr
word.name
#=> "モビリティ"
word.meaning
#=> "(名詞):動きやすさ、可動性"
Mobility.locale = :ru
word.name
#=> nil
word.meaning
#=> nilYou can optionally disable fallbacks to get the real value for a given locale
(for example, to check if a value in a particular locale is set or not) by
passing fallback: false (singular, not plural) to the getter method:
Mobility.locale = :de
word.meaning(fallback: false)
#=> nil
Mobility.locale = :fr
word.meaning(fallback: false)
#=> nil
Mobility.locale = :ja
word.meaning(fallback: false)
#=> "(名詞):動きやすさ、可動性"You can also set the fallback locales for a single read by passing one or more locales:
Mobility.with_locale(:fr) do
word.meaning = "(nf): aptitude à bouger, à se déplacer, à changer, à évoluer"
end
word.save
Mobility.locale = :de
word.meaning(fallback: false)
#=> nil
word.meaning(fallback: :fr)
#=> "(nf): aptitude à bouger, à se déplacer, à changer, à évoluer"
word.meaning(fallback: [:ja, :fr])
#=> "(名詞):動きやすさ、可動性"Also note that passing a locale option into an attribute reader or writer, or
No open issues yet, or sync has not completed.