module Pagy::I18n
def build(*locales)
def build(*locales) locales.each do |locale| locale[:filepath] ||= Pagy.root.join('locales', "#{locale[:locale]}.yml") locale[:pluralize] ||= P11n::LOCALE[locale[:locale]] dictionary = YAML.safe_load(File.read(locale[:filepath], encoding: 'UTF-8')) raise I18nError, %(expected :locale "#{locale[:locale]}" not found in :filepath "#{locale[:filepath].inspect}") \ unless dictionary.key?(locale[:locale]) DATA[locale[:locale]] = [flatten(dictionary[locale[:locale]]), locale[:pluralize]] end end
def flatten(initial, prefix = '')
def flatten(initial, prefix = '') initial.each.reduce({}) do |hash, (key, value)| hash.merge!(value.is_a?(Hash) ? flatten(value, "#{prefix}#{key}.") : { "#{prefix}#{key}" => value }) end end
def load(*locales)
def load(*locales) DATA.clear build(*locales) DATA.freeze end
def translate(locale, key, **opts)
def translate(locale, key, **opts) data, pluralize = DATA[locale] translation = data[key] || (opts[:count] && data[key += ".#{pluralize.call(opts[:count])}"]) \ or return %([translation missing: "#{key}"]) translation.gsub(/%{[^}]+?}/) { |match| opts[:"#{match[2..-2]}"] || match } end