How To Create A Custom I18n Backend For Ruby And Rails

Posted By Weston Ganger

There is surprisingly little documentation on how to create an custom I18n backend for Ruby. Heres an example implementation with comments to help guide you through the process

Custom Exception Handler:

backend_chain = [I18n::Backend::Custom.new]

if Rails.env.development? || Rails.env.test?
  ### Keeps the original YAML backend as a fallback so that local development still works without a populated translation DB
  backend_chain << I18n::Backend::Simple.new

  ### Alternative could be to always have the default locale stored within yml files 
  ### and allow for translations on-top of the default locale file
  ### this would be useful for all environments. For example if a developer adds a new key 
  ### and it is not yet translated in the db. Good for PR workflows
end



I18n.backend = I18n::Backend::Chain.new(*backend_chain)

### Manually add any additional translations here
# I18n.backend.store_translations :en, foo: {bar: {foobar: 'asd'} }

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:October 23, 2021