Module: CMDx::Locale

Extended by:
Locale
Included in:
Locale
Defined in:
lib/cmdx/locale.rb

Overview

Provides internationalization and localization support for CMDx. Handles translation lookups with fallback to the configured locale’s default messages when I18n gem is not available.

Instance Method Summary collapse

Instance Method Details

#translate(key, **options) ⇒ String Also known as: t

Translates a key to the current locale with optional interpolation. Falls back to the configured locale’s YAML file translations if I18n gem is unavailable.

Examples:

Basic translation

Locale.translate("errors.invalid_input")
# => "Invalid input provided"

With interpolation

Locale.translate("welcome.message", name: "John")
# => "Welcome, John!"

With fallback

Locale.translate("missing.key", default: "Custom fallback message")
# => "Custom fallback message"

Parameters:

  • key (String, Symbol)

    The translation key (supports dot notation)

  • options (Hash)

    Translation options

Options Hash (**options):

  • :default (String)

    Fallback message if translation missing

  • :locale (String)

    Target locale (when I18n available)

  • :scope (Hash)

    Translation scope (when I18n available)

  • :* (Object)

    Any other options passed to I18n.t or string interpolation

Returns:

  • (String)

    The translated message

Raises:

  • (ArgumentError)

    When interpolation fails due to missing keys

Rbs:

  • ((String | Symbol) key, **untyped options) -> String



37
38
39
40
41
42
43
44
45
46
# File 'lib/cmdx/locale.rb', line 37

def translate(key, **options)
  options[:default] ||= translation_default(key)
  return ::I18n.t(key, **options) if defined?(::I18n)

  case message = options.delete(:default)
  when String then message % options
  when NilClass then "Translation missing: #{key}"
  else message
  end
end