Add this line to your application's Gemfile:
gem 'i18n_accessors', '~> 0.1.2'
And then execute:
Or install it yourself as:
$ gem install i18n_accessors
To define a set of accessors for a translated attribute of the form
<attribute>_<locale>, include an instance of the
class in your model with translated attribute names as arguments:
class Post def title # ... end def title? # ... end def title=(title) # ... end include I18nAccessors::Methods.new(:title) end
I18n.available_locales will be used to determine which locales to
define accessors for. So if
[:en, :fr], then this
will define methods:
title_fr=. Each of these methods is an alias to
I18n.locale changed to the locale in the suffix.
If you want to specify explicitly which locales to define accessors for, pass
the locales as an option with the
locales key to
new when creating the
def Post # ... include I18nAccessors::Methods.new(:title, :content, locales: [:en, :fr]) end
This will define accessor methods for both
content, in both
en) and French (
I18nAccessors::Missing does a similar thing, but using
respond to messages of the form
<attribute>_<locale>. This is generally
slower (due to how
method_missing works), but can be used to handle any locale:
class Post # ... include I18nAccessors::Missing.new(:title, :content) end
You can include both a
I18nAccessors::Methods module and a
I18nAccessors::Missing module in the same class without conflict (the
accessor methods will take precedence).
If you are using I18nAccessors with Globalize, you can change the default i18n
I18nAccessors.configure do |config| config.i18n_class = Globalize end
With this configuration,
Globalize.with_locale will be used to set the locale
around the accessor methods, rather than
After checking out the repo, run
bin/setup to install dependencies. Then, run
rake spec to run the tests. You can also run
bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run
bundle exec rake install. To release a new version, update the version number in
version.rb, and then run
bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the
.gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/shioyama/i18n_accessors. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.