LocalizableModel allows any ActiveRecord model to have localized attributes.
Add the localizable_model gem to your Gemfile:
gem "localizable_model"Generate the migration:
bin/rails g localizable_model:migrationYou can now define localizable attributes on your model:
class Page < ActiveRecord::Base
localizable do
attribute :name
attribute :body
end
endYou can also use a dictionary. This will let you define attributes dynamically at runtime.
class Page < ActiveRecord::Base
localizable do
dictionary lambda { Page.localizable_attrs }
end
class << self
def localizable_attrs
[:foo, :bar, :baz]
end
end
endUsage examples:
page = Page.create(locale: "en", name: "Hello")
page.name? # => true
page.name.to_s # => "Hello"To get a localized version of a page, call .localize on it:
page = Page.first.localize("en").localize can also take a block argument:
page.localize("nb") do |p|
p.locale # => "nb"
end
p.locale # => "en"Multiple locales can be updated at the same time:
page.name = { en: "Hello", fr: "Bonjour" }By chaining through .any_locale, you can get results from other locales if
a localization is missing.
page = Page.create(locale: "fr", name: "Bonjour").localize("en")
page.any_locale.name? # => true
page.any_locale.name # => "Bonjour"Bug reports, feature requests, and pull requests are welcome. Read CONTRIBUTING.md first. Report security vulnerabilities privately as described in SECURITY.md.
CONTRIBUTING.md also covers how to run the tests and how commits are formatted. This project ships with a code of conduct.
Released under the MIT License.