### Rails Environment Setup for FastGettext Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Include FastGettext translation capabilities in your Rails application and add text domains. This setup should be done after initializers in config/environment.rb. ```Ruby # config/environment.rb after initializers Object.send(:include, FastGettext::Translation) FastGettext.add_text_domain('accounting', path: 'locale') FastGettext.add_text_domain('frontend', path: 'locale') ... ``` -------------------------------- ### Install FastGettext Gem Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Install the FastGettext gem using the RubyGems package manager. ```Bash gem install fast_gettext ``` -------------------------------- ### Define Custom Translation Repository (WTF) Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Example of defining a custom translation repository by inheriting from TranslationRepository::Base or by defining `available_locales` and `pluralisation_rule`. ```Ruby # fast_gettext/translation_repository/wtf.rb module FastGettext module TranslationRepository class Wtf define initialize(name,options), [key], plural(*keys) and either inherit from TranslationRepository::Base or define available_locales and pluralisation_rule end end end ``` -------------------------------- ### Rails Application Controller Setup Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Configure locale settings within your Rails application controller. This includes setting available locales, the default text domain, and the current locale based on request parameters or session. ```Ruby # app/controllers/application_controller.rb class ApplicationController ... include FastGettext::Translation before_filter :set_locale def set_locale FastGettext.available_locales = ['de', 'en', ...] FastGettext.text_domain = 'frontend' FastGettext.set_locale(params[:locale] || session[:locale] || request.env['HTTP_ACCEPT_LANGUAGE']) session[:locale] = I18n.locale = FastGettext.locale end ``` -------------------------------- ### Add Text Domain from YAML Files Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Configure FastGettext to use translations from YAML files, following I18n syntax. Locale files should be named with a `qq.yml` suffix. ```Ruby # A single locale can be segmented in multiple yaml files but they all should be # named with a `qq.yml` suffix, where `qq` is the locale name. FastGettext.add_text_domain('my_app', path: 'config/locales', type: :yaml) ``` -------------------------------- ### Add Text Domain from PO Files Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Configure FastGettext to use translations from .po files. Options to ignore fuzzy translations and report warnings are available. ```Ruby FastGettext.add_text_domain('my_app', path: 'locale', type: :po) # ignore_fuzzy: true to not use fuzzy translations # report_warning: false to hide warnings about obsolete/fuzzy translations ``` -------------------------------- ### Add Text Domain from MO Files Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Configure FastGettext to use translations from .mo files, specifying the text domain and the directory containing the files. ```Ruby FastGettext.add_text_domain('my_app', path: 'locale') ``` -------------------------------- ### Build a Translation Chain Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Create a chain of translation repositories. If a translation is not found in the first repository, FastGettext will query the subsequent ones in the chain. ```Ruby repos = [ FastGettext::TranslationRepository.build('new', path: '....'), FastGettext::TranslationRepository.build('old', path: '....') ] FastGettext.add_text_domain 'combined', type: :chain, chain: repos ``` -------------------------------- ### Build Merge Repositories Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Construct merge repositories, which are similar to chains but optimize translation lookup by selecting and storing the first available translation upon repository addition. ```Ruby repos = [ FastGettext::TranslationRepository.build('new', path: '....'), FastGettext::TranslationRepository.build('old', path: '....') ] domain = FastGettext.add_text_domain 'combined', type: :merge, chain: repos ``` -------------------------------- ### Setting the Locale Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc Demonstrates how to set the current locale for translations using either the 'GetText.locale' class method or the 'set_locale' instance method. ```ruby GetText.locale = "en_US" # translate into english from now on GetText.locale # => en_US ``` ```ruby include GetText set_locale "en_US" ``` -------------------------------- ### Combined Translation Methods Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc Demonstrates combinations of pluralization and context-aware translation methods for comprehensive localization. ```ruby np_("Fruit", "Apple", "%{num} Apples", 3) ``` ```ruby ns_("Fruit|Apple","%{num} Apples", 3) ``` ```ruby np_(["Fruit","Apple","%{num} Apples"], 3) ``` ```ruby ns_(["Fruit|Apple","%{num} Apples"], 3) ``` -------------------------------- ### Add Text Domain from Database Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Configure FastGettext to use translations stored in a database. This approach is scalable and suitable for many locales and translators. It requires loading default models. ```Ruby # db access is cached <-> only first lookup hits the db require "fast_gettext/translation_repository/db" FastGettext::TranslationRepository::Db.require_models # load and include default models FastGettext.add_text_domain('my_app', type: :db, model: TranslationKey) ``` -------------------------------- ### Set Text Domain and Locale Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Set the current text domain and locale for translations. This should be done once per thread. Available locales can be optionally restricted. ```Ruby FastGettext.text_domain = 'my_app' FastGettext.available_locales = ['de', 'en', 'fr', 'en_US', 'en_UK'] # only allow these locales to be set (optional) FastGettext.locale = 'de' ``` -------------------------------- ### Global Multi-Domain Translation Helpers Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Use `TranslationMultidomain` with `D_`, `Dn_`, `Dp_`, `Ds_`, `Dnp_`, and `Dns_` to search for strings across all domains. ```Ruby extend FastGettext::TranslationMultidomain D_("string") # finds 'string' in any domain Dn_("string", "strings", 1) # ditto Dp_("context", "key") Ds_("context|key") Dnp_("context", "string", "strings") Dns_("context|string", "strings") ``` -------------------------------- ### Translation with Context using p_() Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Translate strings with context using the `p_()` or `pgettext()` method. This differentiates translations for the same string used in different contexts. ```Ruby p_('File', 'Open') == _("File\004Open") == "öffnen" p_('Context', 'not-found') == 'not-found' ``` -------------------------------- ### Binding Text Domains Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc Shows how to bind a specific text domain for translations, allowing for different sets of translations (e.g., financial, human-resource terms). ```ruby GetText.bindtextdomain('financial') ``` ```ruby include GetText bindtextdomain('financial') ``` -------------------------------- ### Context-Aware Pluralized Translation with pn_() Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Perform pluralized translations that are also context-aware using the `pn_()` or `pngettext()` method. ```Ruby pn_('Fruit', 'Apple', 'Apples', 3) == 'Äpfel' pn_('Fruit', 'Apple', 'Apples', 1) == 'Apfel' ``` -------------------------------- ### Context-Aware Translation Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc The 'p_()' method provides context-aware translations, useful when a word has multiple meanings. It is equivalent to using 's_()' with a 'context|message' format. ```ruby p_("Printer","Open") <=> p_("File","Open") ``` ```ruby s_("Printer|Open") <=> s_("File|Open") ``` -------------------------------- ### Add Custom Load Path in Rails Source: https://github.com/grosser/fast_gettext/wiki/Howto:-Extending-FastGettext-with-custom-translation-repository Add this to your Rails application's config/application.rb to tell Rails where to search for custom libraries. ```ruby config.autoload_paths += %W(#{config.root}/lib) ``` -------------------------------- ### Basic Translation with _() Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Perform basic string translation using the `_()` or `gettext()` method. If a translation is not found, the original message ID is returned. ```Ruby extend FastGettext::Translation _('Car') == 'Auto' # found translation for 'Car' _('not-found') == 'not-found' # The msgid is returned by default ``` -------------------------------- ### Translation with Namespace using s_() Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Translate strings using a namespace with the `s_()` or `sgettext()` method. This is an alternative to context-based translation, differing mainly in how translations are stored. ```Ruby s_('File|Open') == _('File|Open') == "öffnen" s_('Context|not-found') == 'not-found' ``` -------------------------------- ### Multi-Domain Translation Helpers Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Use `TranslationMultidomain` to access translation functions for specific domains using `d_`, `dn_`, `dp_`, `ds_`, `dnp_`, and `dns_`. ```Ruby extend FastGettext::TranslationMultidomain d_("domainname", "string") # finds 'string' in domain domainname dn_("domainname", "string", "strings", 1) # ditto dp_("domainname", "context", "key") ds_("domainname", "context|key") dnp_("domainname", "context", "string", "strings") dns_("domainname", "context|string", "strings") ``` -------------------------------- ### Register Custom Translation Repository in Rails Console Source: https://github.com/grosser/fast_gettext/wiki/Howto:-Extending-FastGettext-with-custom-translation-repository This snippet shows how to register the custom 'yamlr' translation repository type with FastGettext and add a text domain using it. This is typically done in the Rails console for testing or initialization. ```ruby require 'fast_gettext/translation_repository/yaml_recursive' #=> true FastGettext.add_text_domain('lala', path: 'config/locales', type: :yamlr) #=> { ...our translations ... } ``` -------------------------------- ### Dynamic Translation Availability for Parser Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Use `N_()` and `Nn_()` to make dynamic translations discoverable by the parsing tools. This ensures strings generated at runtime are included in translation files. ```Ruby N_("active"); N_("inactive"); N_("paused") # possible value of status for parser to find. Nn_("active", "inactive", "paused") # alternative method _("Your account is %{account_state}.") % { account_state: _(status) } ``` -------------------------------- ### Logging Missing Translations with Block Default Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Override the `_` method to log missing translation keys when a block default is used and the translation is not found. ```Ruby # Override _ with logging def _(key, &block) result = gettext(key){ nil } # nil returned when not found log_missing_translation_key(key) if result.nil? result || (block ? block.call : key) end ``` -------------------------------- ### Custom Yamlr Translation Repository Module Source: https://github.com/grosser/fast_gettext/wiki/Howto:-Extending-FastGettext-with-custom-translation-repository This Ruby module extends FastGettext's base translation repository to handle YAML files recursively, supporting multiple files per locale. It merges translations from all YAML files found in the specified path. ```ruby require 'fast_gettext/translation_repository/base' require 'yaml' require 'active_support/core_ext/hash/deep_merge.rb' module FastGettext module TranslationRepository # Responsibility: # - find and store yaml files # - provide access to translations in yaml files class Yamlr < Base def initialize(name,options={}) super reload end def available_locales @files.keys end def plural(*keys) ['one', 'other', 'plural2', 'plural3'].map do |name| self[yaml_dot_notation(keys.first, name)] end end def pluralisation_rule self['pluralisation_rule'] ? lambda{|n| eval(self['pluralisation_rule']) } : nil end def reload find_and_store_files(@options) super end protected MAX_FIND_DEPTH = 10 def find_and_store_files(options) @files = {} path = options[:path] || 'config/locales' Dir["#{path}/**/*.yml"].each do |yaml_file| @files.deep_merge!(load_yaml(yaml_file)) end @files end def current_translations @files[FastGettext.locale] || super end # Given a yaml file return a hash of key -> translation def load_yaml(file) yaml = YAML.load_file(file) yaml.keys.reduce({}) do |processed, locale| processed[locale] ||= {} processed[locale].merge!(yaml_hash_to_dot_notation(yaml[locale])) processed end end def yaml_hash_to_dot_notation(yaml_hash) add_yaml_key({}, nil, yaml_hash) end def add_yaml_key(result, prefix, hash) hash.each_pair do |key, value| if value.kind_of?(Hash) add_yaml_key(result, yaml_dot_notation(prefix, key), value) else result[yaml_dot_notation(prefix, key)] = value end end result end def yaml_dot_notation(a,b) a ? "#{a}.#{b}" : b end end end end ``` -------------------------------- ### Basic Translation Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc The basic translation method '_()' translates a given message string. ```ruby _("Hello") ``` -------------------------------- ### Debug Custom Translation Repository Registration Source: https://github.com/grosser/fast_gettext/wiki/Howto:-Extending-FastGettext-with-custom-translation-repository Use this code within an initializer or directly in the Rails console to inspect the result of adding a text domain with the custom 'yamlr' translation repository type. ```ruby puts FastGettext.add_text_domain('lala', path: 'config/locales', type: :yamlr).inspect ``` -------------------------------- ### Reload Merge Repository After Locale Change Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md When using merge repositories, you must explicitly reload the domain whenever the locale changes to ensure translations are loaded correctly for the new locale. ```Ruby FastGettext.locale = 'de' domain.reload ``` -------------------------------- ### Namespace-Aware Pluralized Translation with sn_() Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Perform pluralized translations that are also namespace-aware using the `sn_()` or `sngettext()` method. ```Ruby sn_('Fruit|Apple', 'Apples', 3) == 'Äpfel' sn_('Fruit|Apple', 'Apples', 1) == 'Apfel' ``` -------------------------------- ### Add Logger to Translation Chain Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Add a logger to a translation repository chain to track untranslated or used keys. The callback can be a lambda or any object responding to `call`. ```Ruby repos = [ FastGettext::TranslationRepository.build('app', path: '....') FastGettext::TranslationRepository.build('logger', type: :logger, callback: ->(key_or_array_of_ids) { ... }), } FastGettext.add_text_domain 'combined', type: :chain, chain: repos ``` -------------------------------- ### Parser-Friendly Dynamic Translations Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc The 'N_()' and 'Nn_()' methods are used to make dynamic translation messages readable for the gettext parser, without performing translation at runtime. ```ruby fruit = N_("Apple") # same as fruit = "Apple" _(fruit) # does a normal translation ``` ```ruby fruits = Nn_("Apple", "%{num} Apples") n_(fruits, 3) ``` -------------------------------- ### Block Default for Untranslated Strings Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md When a translation is not found, a provided block is executed and its return value is used. This is useful for long default passages. ```Ruby _('not-found'){ "alternative default" } == alternate default ``` -------------------------------- ### Custom Pluralization Rule Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Define a custom pluralization rule using a Ruby lambda. This is necessary for languages with pluralization rules that differ from the standard English form. ```Ruby FastGettext.pluralisation_rule = ->(count){ count > 5 ? 1 : (count > 2 ? 0 : 2)} ``` -------------------------------- ### Interpolating Pluralized Translations Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Interpolate values into pluralized translation strings using Ruby's '%' operator. This allows dynamic content within plural forms. ```Ruby n_('Car', '%{n} Cars', 2) % { n: count } == '2 Autos' ``` -------------------------------- ### Translation Without Context Fallback Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc The 's_()' method translates a message and, if no translation is found, returns the original message ID. It can also be used with a context prefix. ```ruby s_("Printer|Open") # => "Öffnen" #translation found ``` ```ruby s_("Printer|Open") # => "Open" #translation not found ``` -------------------------------- ### Translate within a Specific Locale Source: https://github.com/grosser/fast_gettext/blob/master/Readme.md Use the `with_locale` method to perform translations in a locale different from the current one. The original locale is restored afterward. ```Ruby FastGettext.with_locale 'gsw_CH' do FastGettext._('Car was successfully created.') end # => "Z auto isch erfolgriich gspeicharat worda." ``` -------------------------------- ### Pluralized Translation Source: https://github.com/grosser/fast_gettext/blob/master/lib/fast_gettext/vendor/README.rdoc The 'n_()' method handles pluralized translations, returning either the singular or plural form based on the provided count. ```ruby n_("Apple", "%{num} Apples", 3) ``` ```ruby n_(["Apple", "%{num} Apples"], 3) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.