transliterate

transliterate(string, replacement = "?")
Instance Public methods

Replaces non-ASCII characters with an ASCII approximation, or if none exists, a replacement character which defaults to â?â.

transliterate('Ãrøskøbing')
# => "AEroskobing"

Default approximations are provided for Western/Latin characters, e.g, âøâ, âñâ, âéâ, âÃâ, etc.

This method is I18n aware, so you can set up custom approximations for a locale. This can be useful, for example, to transliterate German's âüâ and âöâ to âueâ and âoeâ, or to add support for transliterating Russian to ASCII.

In order to make your custom transliterations available, you must set them as the i18n.transliterate.rule i18n key:

# Store the transliterations in locales/de.yml
i18n:
  transliterate:
    rule:
      ü: "ue"
      ö: "oe"

# Or set them using Ruby
I18n.backend.store_translations(:de, i18n: {
  transliterate: {
    rule: {
      'ü' => 'ue',
      'ö' => 'oe'
    }
  }
})

The value for i18n.transliterate.rule can be a simple Hash that maps characters to ASCII approximations as shown above, or, for more complex requirements, a Proc:

I18n.backend.store_translations(:de, i18n: {
  transliterate: {
    rule: ->(string) { MyTransliterator.transliterate(string) }
  }
})

Now you can have different transliterations for each locale:

I18n.locale = :en
transliterate('Jürgen')
# => "Jurgen"

I18n.locale = :de
transliterate('Jürgen')
# => "Juergen"
doc_ruby_on_rails
2015-06-20 00:00:00
Comments
Leave a Comment

Please login to continue.