{"id":13484175,"url":"https://github.com/grosser/fast_gettext","last_synced_at":"2025-05-13T22:03:30.854Z","repository":{"id":504970,"uuid":"132346","full_name":"grosser/fast_gettext","owner":"grosser","description":"Ruby GetText, but 12x faster + 530x less garbage + simple + clean namespace + threadsafe + extendable + multiple backends","archived":false,"fork":false,"pushed_at":"2025-01-06T20:33:11.000Z","size":729,"stargazers_count":407,"open_issues_count":3,"forks_count":82,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-04-25T03:36:40.583Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/grosser.png","metadata":{"files":{"readme":"Readme.md","changelog":"CHANGELOG","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-02-19T07:57:42.000Z","updated_at":"2025-04-24T14:45:09.000Z","dependencies_parsed_at":"2022-07-07T15:21:14.045Z","dependency_job_id":"f4bd7f9c-1a04-411e-99c3-78f299e71a73","html_url":"https://github.com/grosser/fast_gettext","commit_stats":{"total_commits":557,"total_committers":47,"mean_commits":"11.851063829787234","dds":"0.19210053859964094","last_synced_commit":"42ecd724f2a353aab7898ef489d0054606b8ddd3"},"previous_names":[],"tags_count":95,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grosser%2Ffast_gettext","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grosser%2Ffast_gettext/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grosser%2Ffast_gettext/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grosser%2Ffast_gettext/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/grosser","download_url":"https://codeload.github.com/grosser/fast_gettext/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250887328,"owners_count":21503028,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T17:01:20.263Z","updated_at":"2025-04-28T15:25:08.546Z","avatar_url":"https://github.com/grosser.png","language":"Ruby","readme":"FastGettext\n===========\nGetText but 12 x faster, 530 x less garbage, clean namespace (8 vs 26), simple and threadsafe!\n\nIt supports multiple backends (.mo, .po, .yml files, Database(ActiveRecord + any other), Chain, Loggers) and can easily be extended.\n\n[Example Rails application](https://github.com/grosser/gettext_i18n_rails_example)\n\n\nComparison\n==========\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003c/td\u003e\n    \u003ctd width=\"100\"\u003eHash\u003c/td\u003e\n    \u003ctd width=\"150\"\u003eFastGettext\u003c/td\u003e\n    \u003ctd width=\"100\"\u003eGetText\u003c/td\u003e\n    \u003ctd width=\"100\"\u003eActiveSupport I18n::Simple\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003eSpeed*\u003c/td\u003e\n    \u003ctd\u003e0.08s\u003c/td\u003e\n    \u003ctd\u003e0.14s\u003c/td\u003e\n    \u003ctd\u003e1.75s\u003c/td\u003e\n    \u003ctd\u003e3.75s\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003eObjects*\u003c/td\u003e\n    \u003ctd\u003e11K\u003c/td\u003e\n    \u003ctd\u003e15K\u003c/td\u003e\n    \u003ctd\u003e8017K\u003c/td\u003e\n    \u003ctd\u003e7107K\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003eIncluded backends\u003c/td\u003e\n    \u003ctd\u003e\u003c/td\u003e\n    \u003ctd\u003edb, yml, mo, po, logger, chain\u003c/td\u003e\n    \u003ctd\u003emo\u003c/td\u003e\n    \u003ctd\u003eyml (db/key-value/po/chain in other I18n backends)\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\u003csmall\u003e*500.000 translations with ruby 2.5.3 through `bundle exec rake benchmark`\u003c/small\u003e\n\n\nSetup\n=====\n\n### 1. Install\n\n```Bash\ngem install fast_gettext\n```\n\n### 2. Add a translation repository\n\nFrom mo files (traditional/default)\n\n```Ruby\nFastGettext.add_text_domain('my_app', path: 'locale')\n```\n\nOr po files (less maintenance than mo)\n\n```Ruby\nFastGettext.add_text_domain('my_app', path: 'locale', type: :po)\n# ignore_fuzzy: true to not use fuzzy translations\n# report_warning: false to hide warnings about obsolete/fuzzy translations\n```\n\nOr yaml files (use I18n syntax/indentation)\n\n```Ruby\n# A single locale can be segmented in multiple yaml files but they all should be\n# named with a `qq.yml` suffix, where `qq` is the locale name.\nFastGettext.add_text_domain('my_app', path: 'config/locales', type: :yaml)\n```\n\nOr database (scaleable, good for many locales/translators)\n\n```Ruby\n# db access is cached \u003c-\u003e only first lookup hits the db\nrequire \"fast_gettext/translation_repository/db\"\nFastGettext::TranslationRepository::Db.require_models # load and include default models\nFastGettext.add_text_domain('my_app', type: :db, model: TranslationKey)\n```\n\n### 3. Choose text domain and locale for translation\nDo this once in every Thread. (e.g. Rails -\u003e ApplicationController)\n\n```Ruby\nFastGettext.text_domain = 'my_app'\nFastGettext.available_locales = ['de', 'en', 'fr', 'en_US', 'en_UK'] # only allow these locales to be set (optional)\nFastGettext.locale = 'de'\n```\n\n### 4. Start translating\n\nFastGettext supports all the translation methods of [ruby-gettext](http://github.com/ruby-gettext/gettext) with added support for block defaults.\n(to get `*gettext` methods, use `FastGettext::TranslationAliased`)\n\n#### `_()` or `gettext()`: basic translation\n\n```ruby\nextend FastGettext::Translation\n_('Car') == 'Auto'             # found translation for 'Car'\n_('not-found') == 'not-found'  # The msgid is returned by default\n```\n\n#### `n_()` or `ngettext()`: pluralization\n\n```ruby\nn_('Car', 'Cars', 1) == 'Auto'\nn_('Car', 'Cars', 2) == 'Autos' # German plural of Cars\n```\n\nYou'll often want to interpolate the results of `n_()` using ruby builtin `%` operator.\n\n```ruby\nn_('Car', '%{n} Cars', 2) % { n: count } == '2 Autos'\n```\n\n#### `p_()` or `pgettext()`: translation with context\n\n```ruby\np_('File', 'Open') == _(\"File\\004Open\") == \"öffnen\"\np_('Context', 'not-found') == 'not-found'\n```\n\n#### `s_()` or `sgettext()`: translation with namespace\n\n```ruby\ns_('File|Open') == _('File|Open') == \"öffnen\"\ns_('Context|not-found') == 'not-found'\n```\n\nThe difference between `s_()` and `p_()` is largely based on how the translations\nare stored. Your preference will be based on your workflow and translation editing\ntools.\n\n#### `pn_()` or `pngettext()`: context-aware pluralized\n\n```ruby\npn_('Fruit', 'Apple', 'Apples', 3) == 'Äpfel'\npn_('Fruit', 'Apple', 'Apples', 1) == 'Apfel'\n```\n\n#### `sn_()` or `sngettext()`: without context pluralized\n\n```ruby\nsn_('Fruit|Apple', 'Apples', 3) == 'Äpfel'\nsn_('Fruit|Apple', 'Apples', 1) == 'Apfel'\n```\n\n#### `N_()` and `Nn_()`: make dynamic translations available to the parser.\n\nIn many instances, your strings will not be found by the ruby parsing. These methods\nallow for those strings to be discovered.\n\n```\nN_(\"active\"); N_(\"inactive\"); N_(\"paused\") # possible value of status for parser to find.\nNn_(\"active\", \"inactive\", \"paused\")        # alternative method\n_(\"Your account is %{account_state}.\") % { account_state: _(status) }\n```\n\n\nManaging translations\n=====================\n\n### mo/po-files\nGenerate .po or .mo files using GetText parser (example tasks at [gettext_i18n_rails](http://github.com/grosser/gettext_i18n_rails))\n\nTell Gettext where your .mo or .po files lie, e.g. for locale/de/my_app.po and locale/de/LC_MESSAGES/my_app.mo\n\n```Ruby\nFastGettext.add_text_domain('my_app', path: 'locale')\n```\n\nUse the [original GetText](http://github.com/ruby-gettext/gettext) to create and manage po/mo-files.\n(Work on a po/mo parser \u0026 reader that is easier to use has started, contributions welcome @ [get_pomo](http://github.com/grosser/get_pomo) )\n\n### Database\n[Example migration for ActiveRecord](http://github.com/grosser/fast_gettext/blob/master/examples/db/migration.rb)\u003cbr/\u003e\nThe default plural separator is `||||` but you may overwrite it (or suggest a better one...).\n\nThis is usable with any model DataMapper/Sequel or any other(non-database) backend, the only thing you need to do is respond to the self.translation(key, locale) call.\nIf you want to use your own models, have a look at the [default models](http://github.com/grosser/fast_gettext/tree/master/lib/fast_gettext/translation_repository/db_models) to see what you want/need to implement.\n\nTo manage translations via a Web GUI, use a [Rails application and the translation_db_engine](http://github.com/grosser/translation_db_engine)\n\nRails\n=======================\nTry the [gettext_i18n_rails plugin](http://github.com/grosser/gettext_i18n_rails), it simplifies the setup.\u003cbr/\u003e\nTry the [translation_db_engine](http://github.com/grosser/translation_db_engine), to manage your translations in a db.\n\nSetting `available_locales`,`text_domain` or `locale` will not work inside the `environment.rb`,\nsince it runs in a different thread then e.g. controllers, so set them inside your application_controller.\n\n```Ruby\n# config/environment.rb after initializers\nObject.send(:include, FastGettext::Translation)\nFastGettext.add_text_domain('accounting', path: 'locale')\nFastGettext.add_text_domain('frontend', path: 'locale')\n...\n\n# app/controllers/application_controller.rb\nclass ApplicationController ...\n  include FastGettext::Translation\n  before_filter :set_locale\n  def set_locale\n    FastGettext.available_locales = ['de', 'en', ...]\n    FastGettext.text_domain = 'frontend'\n    FastGettext.set_locale(params[:locale] || session[:locale] || request.env['HTTP_ACCEPT_LANGUAGE'])\n    session[:locale] = I18n.locale = FastGettext.locale\n  end\n```\n\n\nAdvanced features\n=================\n\n### Abnormal pluralisation\nPlurals are selected by index, think of it as `['car', 'cars'][index]`\u003cbr/\u003e\nA pluralisation rule decides which form to use e.g. in english its `count == 1 ? 0 : 1`.\u003cbr/\u003e\nIf you have any languages that do not fit this rule, you have to add a custom pluralisation rule.\n\nVia Ruby:\n\n```Ruby\nFastGettext.pluralisation_rule = -\u003e(count){ count \u003e 5 ? 1 : (count \u003e 2 ? 0 : 2)}\n```\n\nVia mo/pofile:\n\n```\nPlural-Forms: nplurals=2; plural=n==2?3:4;\n```\n\n[Plural expressions for all languages](http://translate.sourceforge.net/wiki/l10n/pluralforms).\n\n### default_text_domain\nIf you only use one text domain, setting `FastGettext.default_text_domain = 'app'`\nis sufficient and no more `text_domain=` is needed\n\n### default_locale\nIf the simple rule of \"first `available_locale` or 'en'\" is not sufficient for you, set `FastGettext.default_locale = 'de'`.\n\n### default_available_locales\nFallback when no available_locales are set\n\n### with_locale\nIf there is content from different locales that you wish to display, you should use the with_locale option as below:\n\n```Ruby\nFastGettext.with_locale 'gsw_CH' do\n  FastGettext._('Car was successfully created.')\nend\n# =\u003e \"Z auto isch erfolgriich gspeicharat worda.\"\n```\n\n### Chains\nYou can use any number of repositories to find a translation. Simply add them to a chain and when\nthe first cannot translate a given key, the next is asked and so forth.\n\n```Ruby\nrepos = [\n  FastGettext::TranslationRepository.build('new', path: '....'),\n  FastGettext::TranslationRepository.build('old', path: '....')\n]\nFastGettext.add_text_domain 'combined', type: :chain, chain: repos\n```\n\n### Merge\nIn some cases you can benefit from using merge repositories as an alternative to chains. They behave nearly the same. The difference is in the internal\ndata structure. While chain repos iterate over the whole chain for each translation, merge repositories select and store the first translation at the time\na subordinate repository is added. This puts the burden on the load phase and speeds up the translations.\n\n```Ruby\nrepos = [\n  FastGettext::TranslationRepository.build('new', path: '....'),\n  FastGettext::TranslationRepository.build('old', path: '....')\n]\ndomain = FastGettext.add_text_domain 'combined', type: :merge, chain: repos\n```\n\nDownside of this approach is that you have to reload the merge repo each time a language is changed.\n\n```Ruby\nFastGettext.locale = 'de'\ndomain.reload\n```\n\n### Logger\nWhen you want to know which keys could not be translated or were used, add a Logger to a Chain:\n\n```Ruby\nrepos = [\n  FastGettext::TranslationRepository.build('app', path: '....')\n  FastGettext::TranslationRepository.build('logger', type: :logger, callback: -\u003e(key_or_array_of_ids) { ... }),\n}\nFastGettext.add_text_domain 'combined', type: :chain, chain: repos\n```\n\nIf the Logger is in position #1 it will see all translations, if it is in position #2 it will only see the unfound.\nUnfound may not always mean missing, if you choose not to translate a word because the key is a good translation, it will appear nevertheless.\nA lambda or anything that responds to `call` will do as callback. A good starting point may be `examples/missing_translations_logger.rb`.\n\n### Plugins\nWant an xml version?\nWrite your own TranslationRepository!\n\n```Ruby\n# fast_gettext/translation_repository/wtf.rb\nmodule FastGettext\n  module TranslationRepository\n    class Wtf\n      define initialize(name,options), [key], plural(*keys) and\n      either inherit from TranslationRepository::Base or define available_locales and pluralisation_rule\n    end\n  end\nend\n```\n\n### Multi domain support\n\nIf you have more than one gettext domain, there are two sets of functions\navailable:\n\n```Ruby\nextend FastGettext::TranslationMultidomain\n\nd_(\"domainname\", \"string\") # finds 'string' in domain domainname\ndn_(\"domainname\", \"string\", \"strings\", 1) # ditto\ndp_(\"domainname\", \"context\", \"key\")\nds_(\"domainname\", \"context|key\")\ndnp_(\"domainname\", \"context\", \"string\", \"strings\")\ndns_(\"domainname\", \"context|string\", \"strings\")\n```\n\nThese are helper methods so you don't need to write:\n\n```Ruby\nFastGettext.with_domain(\"domainname\") { _(\"string\") }\n```\n\nIt is useful in Rails plugins in the views for example. The second set of\nfunctions are D functions which search for string in _all_ domains. If there\nare multiple translations in different domains, it returns them in random\norder (depends on the Ruby hash implementation).\n\n```Ruby\nextend FastGettext::TranslationMultidomain\n\nD_(\"string\") # finds 'string' in any domain\nDn_(\"string\", \"strings\", 1) # ditto\nDp_(\"context\", \"key\")\nDs_(\"context|key\")\nDnp_(\"context\", \"string\", \"strings\")\nDns_(\"context|string\", \"strings\")\n```\n\nAlternatively you can use [merge repository](https://github.com/grosser/fast_gettext#merge) to achieve the same behavior.\n\n#### Block defaults\n\nAll the translation methods (including MultiDomain) support a block default, a feature not provided by ruby-gettext.  When a translation is\nnot found, if a block is provided the block is always returned. Otherwise, a key is returned. Methods doing pluralization will attempt a simple translation of alternate keys.\n\n```ruby\n_('not-found'){ \"alternative default\" } == alternate default\n```\n\nThis block default is useful when the default is a very long passage of text that wouldn't make a useful key. You can also instrument logging not found keys.\n\n```ruby\n_('terms-and-conditions'){\n  load_terms_and_conditions\n  request_terms_and_conditions_translation_from_legal\n}\n\n# Override _ with logging\ndef _(key, \u0026block)\n  result = gettext(key){ nil } # nil returned when not found\n  log_missing_translation_key(key) if result.nil?\n  result || (block ? block.call : key)\nend\n```\n\n\nFAQ\n===\n - [Problems with ActiveRecord messages?](http://wiki.github.com/grosser/fast_gettext/activerecord)\n - [Iconv require error in 1.9.2](http://exceptionz.wordpress.com/2010/02/03/how-to-fix-the-iconv-require-error-in-ruby-1-9)\n\n\nAuthors\n=======\nMo/Po-file parsing from Masao Mutoh, see vendor/README\n\n### [Contributors](http://github.com/grosser/fast_gettext/contributors)\n - [geekq](http://www.innoq.com/blog/vd)\n - [Matt Sanford](http://blog.mzsanford.com)\n - [Antonio Terceiro](http://softwarelivre.org/terceiro)\n - [J. Pablo Fernández](http://pupeno.com)\n - Rudolf Gavlas\n - [Ramón Cahenzli](http://www.psy-q.ch)\n - [Rainux Luo](http://rainux.org)\n - [Dmitry Borodaenko](https://github.com/angdraug)\n - [Kouhei Sutou](https://github.com/kou)\n - [Hoang Nghiem](https://github.com/hoangnghiem)\n - [Costa Shapiro](https://github.com/costa)\n - [Jamie Dyer](https://github.com/kernow)\n - [Stephan Kulow](https://github.com/coolo)\n - [Fotos Georgiadis](https://github.com/fotos)\n - [Lukáš Zapletal](https://github.com/lzap)\n - [Dominic Cleal](https://github.com/domcleal)\n - [Tomas Strachota](https://github.com/tstrachota)\n - [Martin Meier](https://github.com/mameier)\n - [morcoteg](https://github.com/morcoteg)\n - [Daniel Schepers](https://github.com/tall-dan)\n - [Robert Graff](https://github.com/rgraff)\n - [Peter Leitzen](https://github.com/splattael)\n\n[Michael Grosser](http://grosser.it)\u003cbr/\u003e\nmichael@grosser.it\u003cbr/\u003e\nLicense: MIT, some vendor parts under the same license terms as Ruby (see headers)\u003cbr/\u003e\n[![CI](https://github.com/grosser/fast_gettext/actions/workflows/actions.yml/badge.svg)](https://github.com/grosser/fast_gettext/actions/workflows/actions.yml)\n","funding_links":[],"categories":["Ruby","Internationalization"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgrosser%2Ffast_gettext","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgrosser%2Ffast_gettext","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgrosser%2Ffast_gettext/lists"}