• Stars
    star
    257
  • Rank 153,488 (Top 4 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 15 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Rails: FastGettext, I18n integration -- simple, threadsafe and fast!

FastGettext / Rails integration.

Translate via FastGettext, use any other I18n backend as extension/fallback.

Rails does: I18n.t('syntax.with.lots.of.dots') with nested yml files We do: _('Just translate my damn text!') with simple, flat mo/po/yml files or directly from db To use I18n calls add a syntax.with.lots.of.dots translation.

See it working in the example application.

Setup

Installation

# Gemfile
gem 'gettext_i18n_rails'
Optional:

Add gettext if you want to find translations or build .mo files
Add ruby_parser if you want to find translations inside haml/slim files

# Gemfile
gem 'gettext', '>=3.0.2', :require => false
gem 'ruby_parser', :require => false, :group => :development
Add first language:

Add the first language using:

rake gettext:add_language[XX]

or

LANGUAGE=[XX] rake gettext:add_language

where XX is the ISO 639-1 2-letter code for the language you want to create.

This will also create the locale directory (where the translations are being stored) and run gettext:find to find any strings marked for translation.

You can, of course, add more languages using the same command.

Locales & initialisation

Copy default locales with dates/sentence-connectors/AR-errors you want from e.g. rails i18n into 'config/locales'

To initialize:

# config/initializers/fast_gettext.rb
FastGettext.add_text_domain 'app', :path => 'locale', :type => :po
FastGettext.default_available_locales = ['en','de'] #all you want to allow
FastGettext.default_text_domain = 'app'

And in your application:

# app/controllers/application_controller.rb
class ApplicationController < ...
  before_action :set_gettext_locale

Translating

Performance is almost the same for all backends since translations are cached after first use.

Option A: .po files

FastGettext.add_text_domain 'app', :path => 'locale', :type => :po
  • use some _('translations')
  • run rake gettext:find, to let GetText find all translations used
  • (optional) run rake gettext:store_model_attributes, to parse the database for columns that can be translated
  • if this is your first translation: cp locale/app.pot locale/de/app.po for every locale you want to use
  • translate messages in 'locale/de/app.po' (leave msgstr blank and msgstr == msgid)

New translations will be marked "fuzzy", search for this and remove it, so that they will be used. Obsolete translations are marked with ~#, they usually can be removed since they are no longer needed

Unfound translations with rake gettext:find

Dynamic translations like _("x"+"u") cannot be found. You have 4 options:

  • add N_('xu') somewhere else in the code, so the parser sees it
  • add N_('xu') in a totally separate file like locale/unfound_translations.rb, so the parser sees it
  • use the gettext_test_log rails plugin to find all translations that where used while testing
  • add a Logger to a translation Chain, so every unfound translations is logged (example)

Option B: Traditional .po/.mo files

FastGettext.add_text_domain 'app', :path => 'locale'
  • follow Option A
  • run rake gettext:pack to write binary GetText .mo files

Option C: Database

Most scalable method, all translators can work simultaneously and online.

Easiest to use with the translation database Rails engine. Translations can be edited under /translation_keys

FastGettext::TranslationRepository::Db.require_models
FastGettext.add_text_domain 'app', :type => :db, :model => TranslationKey

I18n

I18n.locale <==> FastGettext.locale.to_sym
I18n.locale = :de <==> FastGettext.locale = 'de'

Any call to I18n that matches a gettext key will be translated through FastGettext.

Namespaces

Car|Model means Model in namespace Car. You do not have to translate this into english "Model", if you use the namespace-aware translation

s_('Car|Model') == 'Model' #when no translation was found

XSS / html_safe

If you trust your translators and all your usages of % on translations:

# config/environment.rb
GettextI18nRails.translations_are_html_safe = true

String % vs html_safe is buggy
My recommended fix is: require 'gettext_i18n_rails/string_interpolate_fix'

  • safe stays safe (escape added strings)
  • unsafe stays unsafe (do not escape added strings)

ActiveRecord - error messages

ActiveRecord error messages are translated through Rails::I18n, but model names and model attributes are translated through FastGettext. Therefore a validation error on a BigCar's wheels_size needs _('big car') and _('BigCar|Wheels size') to display localized.

The model/attribute translations can be found through rake gettext:store_model_attributes, (which ignores some commonly untranslated columns like id,type,xxx_count,...).

Error messages can be translated through FastGettext, if the ':message' is a translation-id or the matching Rails I18n key is translated.

Option A:

Define a translation for "I need my rating!" and use it as message.

validates_inclusion_of :rating, :in=>1..5, :message=>N_('I need my rating!')

Option B:

validates_inclusion_of :rating, :in=>1..5

Make a translation for the I18n key: activerecord.errors.models.rating.attributes.rating.inclusion

Option C:

Add a translation to each config/locales/*.yml files

en:
  activerecord:
    errors:
      models:
        rating:
          attributes:
            rating:
              inclusion: " -- please choose!"

The rails I18n guide can help with Option B and C.

Plurals

FastGettext supports pluralization

n_('Apple','Apples',3) == 'Apples'

Abnormal plurals like e.g. Polish that has 4 different can also be addressed, see FastGettext Readme

Customizing list of translatable files

When you run

rake gettext:find

by default the following files are going to be scanned for translations: {app,lib,config,locale}/**/*.{rb,erb,haml,slim}. If you want to specify a different list, you can redefine files_to_translate in the gettext namespace in a file like lib/tasks/gettext.rake:

namespace :gettext do
  def files_to_translate
    Dir.glob("{app,lib,config,locale}/**/*.{rb,erb,haml,slim,rhtml}")
  end
end

Customizing text domains setup task

By default a single application text domain is created (named app or if you load the environment the value of FastGettext.text_domain is being used).

If you want to have multiple text domains or change the definition of the text domains in any way, you can do so by overriding the :setup task in a file like lib/tasks/gettext.rake:

# Remove the provided gettext setup task
Rake::Task["gettext:setup"].clear

namespace :gettext do
  task :setup => [:environment] do
    domains = Application.config.gettext["domains"]

    domains.each do |domain, options|
      files = Dir.glob(options["paths"])

      GetText::Tools::Task.define do |task|
        task.package_name = options["name"]
        task.package_version = "1.0.0"
        task.domain = options["name"]
        task.po_base_directory = locale_path
        task.mo_base_directory = locale_path
        task.files = files
        task.enable_description = false
        task.msgmerge_options = gettext_msgmerge_options
        task.msgcat_options = gettext_msgcat_options
        task.xgettext_options = gettext_xgettext_options
      end
    end
  end
end

Changing msgmerge, msgcat, and xgettext options

The default options for parsing and create .po files are:

--sort-by-msgid --no-location --no-wrap

These options sort the translations by the msgid (original / source string), don't add location information in the po file and don't wrap long message lines into several lines.

If you want to override them you can put the following into an initializer like config/initializers/gettext.rb:

Rails.application.config.gettext_i18n_rails.msgmerge = %w[--no-location]
Rails.application.config.gettext_i18n_rails.msgcat = %w[--no-location]
Rails.application.config.gettext_i18n_rails.xgettext = %w[--no-location]

or

Rails.application.config.gettext_i18n_rails.default_options = %w[--no-location]

to override both.

You can see the available options by running rgettext -h, rmsgcat -f and rxgettext -h.

Use I18n instead Gettext to ActiveRecord/ActiveModel translations

If you want to disable translations to model name and attributes you can put the following into an initializer like config/initializers/gettext.rb:

Rails.application.config.gettext_i18n_rails.use_for_active_record_attributes = false

And now you can use your I18n yaml files instead.

Using your translations from javascript

If want to use your .PO files on client side javascript you should have a look at the GettextI18nRailsJs extension.

Contributors

Michael Grosser
[email protected]
License: MIT
Build Status

More Repositories

1

parallel

Ruby: parallel processing made simple and fast
Ruby
4,052
star
2

parallel_tests

Ruby: 2 CPUs = 2x Testing Speed for RSpec, Test::Unit and Cucumber
Ruby
3,257
star
3

pru

Pipeable Ruby - forget about grep / sed / awk / wc ... use pure, readable Ruby!
Ruby
579
star
4

smusher

Ruby/CLI: Automatic lossless reduction of all your images
Ruby
555
star
5

maxitest

Minitest + all the features you always wanted.
Ruby
441
star
6

fast_gettext

Ruby GetText, but 12x faster + 530x less garbage + simple + clean namespace + threadsafe + extendable + multiple backends
Ruby
390
star
7

wwtd

WWTD: Travis simulator - faster + no more waiting for build emails
Ruby
366
star
8

rspec-instafail

Show failing specs instantly
Ruby
272
star
9

test_after_commit

Make after_commit callbacks fire in tests for Rails 3+ with transactional_fixtures = true.
Ruby
240
star
10

rpx_now

Ruby: RPXNow.com user login/creation and view helpers Facebook, Twitter, Google, MSN, OpenID, MySpace, Yahoo -- All in One
Ruby
230
star
11

single_cov

Actionable code coverage.
Ruby
226
star
12

bitfields

n Booleans = 1 Integer, saves columns and migrations.
Ruby
221
star
13

i18n_data

Ruby: country/language names and 2-letter-code pairs, in 85 languages, for country/language i18n
Ruby
186
star
14

vendorer

Vendorer keeps your dependencies documented, cached and up to date
Ruby
186
star
15

ar_after_transaction

Execute irreversible actions only when transactions are not rolled back
Ruby
155
star
16

url_store

Data securely stored in urls.
Ruby
146
star
17

kennel

Datadog monitors/dashboards/slos as code, avoid chaotic management via UI
Ruby
128
star
18

ruco

Desktop-style, Intuitive, Commandline Editor in Ruby. "Better than nano, simpler than vim."
Ruby
125
star
19

programming_pearls

eBook: Programming Pearls Rewritten in Ruby
Ruby
108
star
20

easy_esi

Rails: Cached pages with updated partials
Ruby
106
star
21

reduce

Ruby/CLI: minify javascript + stylesheets, lossless image optimization
JavaScript
90
star
22

git-autobisect

Find the first broken commit without having to learn git bisect
Ruby
84
star
23

parallel_split_test

Split a big test file into multiple chunks and run them in parallel
Ruby
81
star
24

tic_tac_toe

Play Tic-Tac-Toe in Ruby using Curses(full-screen-commandline app)
Ruby
71
star
25

sort_alphabetical

Ruby: sort UTF8 Strings alphabetical via Enumerable extension
Ruby
69
star
26

youtube_search

Search youtube via this simple ruby api
Ruby
67
star
27

soft_deletion

Explicit soft deletion for ActiveRecord via deleted_at and default scope
Ruby
67
star
28

simple_auto_complete

Rails: Simple, customizable, unobstrusive - Autocomplete
JavaScript
64
star
29

dispel

Ruby: Remove evil curses
Ruby
63
star
30

preoomkiller

Softly kills your process with SIGTERM before it runs out of memory.
Ruby
63
star
31

single_test

Rake tasks to invoke single tests/specs with rakish syntax
Ruby
60
star
32

dotfiles

Clean and powerful dotfiles -- bash / git / ruby / irb / nano / ruco
Shell
57
star
33

bundler-organization_audit

Automatic Gemfile security audit for all your organizaition/user repos
Ruby
52
star
34

fallback

Fallback when original attribute is not present or somethings not right.
Ruby
47
star
35

record_activities

Rails: Record user activities without controller helpers, build on top of userstamps plugin
Ruby
47
star
36

ie_iframe_cookies

Rails: Normal cookies inside IFrames for IE via P3P headers
Ruby
45
star
37

cachy

Ruby: Caching library to simplify and organize caching
Ruby
44
star
38

zombie_passenger_killer

Guaranteed zombie passengers death.
Ruby
44
star
39

tracked_plugins

script/plugin now keeps track of installation, can list urls/revisions/install-dates/plugin-locally-hacked? and update.
Ruby
43
star
40

stub_server

Boot up a real server to serve testing replies
Ruby
43
star
41

rails2_asset_pipeline

Familiar asset handling for those stuck on Rails 2
Ruby
41
star
42

request_recorder

Record your rack/rails requests and store them for future inspection
Ruby
40
star
43

ar_merge

Merge 2 ActiveRecords, preserving attributes, associations and counters
Ruby
40
star
44

gem-dependent

How many gems depend on your gem ?
Ruby
39
star
45

travis_dedup

Stop all builds on the same PR when a new job starts
Ruby
38
star
46

safe_regexp

Ruby Regex Timeout / Backtracking Bomb Safety
Ruby
30
star
47

translation_db_engine

Rails/AR: engine to manage translations inside a database
Ruby
30
star
48

rubinjam

Covert ruby gem to universal cross-platform binary
Ruby
30
star
49

gettext_i18n_rails_example

Rails example application using FastGettext + gettext_i18n_rails + gettext_test_log
Ruby
29
star
50

url_to_media_tag

Convert an Youtube/Vimeo/Image... Url to image or video embed.
Ruby
27
star
51

forking_test_runner

Run every test in a fork to avoid pollution and get clean output per test
Ruby
27
star
52

restful_catch_all_route

One rule for complete restful routing, no helpers, no worries.
Ruby
26
star
53

scopify

Add named scopes and chainable scopes to any Object / Model.
Ruby
24
star
54

key_value

Abuse Sql database as Key-Value Store
Ruby
22
star
55

acts_as_feed

Rails/AR: Transform a Model into a Feed Representation (Feed Reader)
Ruby
22
star
56

sinatra-magick

Sinatra app to manipulate images given by url via mini_magick and image_magick. completly evented
Ruby
22
star
57

concern

Ruby: Seperation of concerns without meta-madness and namespace pollution.
Ruby
22
star
58

has_a_location

AR: Easy location (lat/long) handling + in_radius + find on a given map section
Ruby
22
star
59

virtual_asset_path

Improve Rails Asset Caching with MD5 and virtual folders
Ruby
21
star
60

s3_slider

jQuery: slideshow displaying images + description, ~1kb for js+css, simple and elegant
HTML
21
star
61

git-whence

Find the merge and pull request a commit came from + fuzzy search for cherry-picks
Ruby
21
star
62

readable_random

Ruby: Readable random strings for coupons or tokens
Ruby
20
star
63

s3_meta_sync

Efficiently sync folders with s3 using a metadata file with md5 sums.
Ruby
20
star
64

testrbl

Run ruby Minitest/Test::Unit/Spec/Shoulda tests by line-number / files / folder
Ruby
20
star
65

countries_and_languages

Rails: Countries and languages in I18n.locale for select_tag or output in 85 languages
Ruby
19
star
66

autoscaling

Amazon AWS/EC2 autoscaling All in one
Shell
19
star
67

helpful_fields

Simple & Helpful Field Helpers for Rails e.g. check_box_with_label or prefilled fields from params
Ruby
18
star
68

go-testcov

`go test` that fails on uncovered lines and shows them
Go
18
star
69

cleanser

Find polluting test by bisecting your tests.
Ruby
17
star
70

repo_dependency_graph

Graph the dependencies of your repositories
Ruby
16
star
71

get_pomo

Ruby/Gettext: A .mo and .po file parser/generator
Ruby
16
star
72

honeypot

Rails: Simple honeypots
Ruby
16
star
73

random_records

Rails/AR: Fast random records for ActiveRecord
Ruby
16
star
74

rpx_now_example

Example Rails app using RPXNow plugin
Ruby
16
star
75

logrecycler

Re-process logs from applications you cannot modify to convert them to json and add prometheus/stats metrics
Go
15
star
76

after_commit_exception_notification

Rails: Get notified when an after_commit block blows up
Ruby
15
star
77

textpow

Read TextMate syntax files and parse text with them
Ruby
14
star
78

codeclimate_batch

Report a batch of codeclimate results by merging and from multiple servers
Ruby
13
star
79

dockerb

Dockerfile.erb - use ruby in your dynamic Dockerfile
Ruby
12
star
80

cia

Central Internal Auditing: Audit model events like update/create/delete + attribute changes + grouped them by transaction, in normalized table layout for easy query access.
Ruby
12
star
81

cc-amend

Unify reports from all your tests runs and send them as one.
Ruby
12
star
82

gem_of_thrones

Everybody wants to be king, but only one can rule (synchronized via a distributed cache)
Ruby
12
star
83

github-grep

Grep through github search results
Ruby
11
star
84

kube-leader

Simple Kubernetes Leader Election via ConfigMap as ENTRYPOINT
Go
10
star
85

travis_cron

Run travis as cron (also supports travis PRO)
Ruby
10
star
86

air_man

Email notifications for high-frequency Airbrake errors
Ruby
10
star
87

gem_on_demand

Run your own gem server that fetches from github, uses tags as version and builds gems on demand
Ruby
9
star
88

i18n-backend-http

Rails I18n Backend for Http APIs with etag-aware distributed background polling and lru-memory+[memcache] caching.
Ruby
9
star
89

matching_bundle

Find a matching bundler version for a Gemfile and use it
Ruby
9
star
90

active_record-comments

Add comments to ActiveRecord queries to see where they came from or what user caused them
Ruby
9
star
91

translated_attributes

AR/Rails translatable attributes through virtual fields
Ruby
9
star
92

cmd2json

Covert command output and exit status to json to pipe them atomically into logs
Ruby
8
star
93

autolang

Automatic translation to a new language for Gettext/JSON using Google translate
Ruby
8
star
94

db_graph

Easy graphs from AR date fields
Ruby
8
star
95

organization_license_audit

Audit all licenses used by your github organization/user
Ruby
8
star
96

ruby-cli-daemon

Make all gem executables execute instantly
Ruby
8
star
97

ar_multi_threaded_transactional_tests

Execute multithreaded code while still using transactional fixtures by synchronizing db access to a single connection
Ruby
8
star
98

rhr

Ruby Hypertext Refinement -- the ease of PHP with the elegance of Ruby
Ruby
7
star
99

git-graph

Date porn from your git history
Ruby
7
star
100

unicorn_wrangler

Unicorn: out of band GC / restart on max memory bloat / restart after X requests
Ruby
7
star