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 default English 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 English 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



40
41
42
43
44
45
46
47
48
49
# File 'lib/cmdx/locale.rb', line 40

def translate(key, **options)
  options[:default] ||= EN.dig("en", *key.to_s.split("."))
  return ::I18n.t(key, **options) if defined?(::I18n)

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