Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for locale value objects #679

Open
viralpraxis opened this issue Jan 17, 2024 · 0 comments
Open

Add support for locale value objects #679

viralpraxis opened this issue Jan 17, 2024 · 0 comments

Comments

@viralpraxis
Copy link

We use custom classes (value objects) to represent application-level locales:

# frozen_string_literal: true

class Locale
  attr_reader :code

  delegate :to_sym, to: :code

  def self.[](code)
    new(code: code)
  end

  def initialize(code:)
    @code = code.to_sym
  end

  ...
end

And pass it to I18n: I18n.t(..., locale: Locale[:en]).

While this approach is quite handy (there are, actually, additional Locale attributes; it can be integrated to ActiveRecord and ActiveModel and what not), it's a bit flaky (it depends on MRI implementation details) -- it works on 2.7.4 and does not on 3.0.0.

Seems like the only problem is method

def enforce_available_locales!(locale)
  if locale != false && config.enforce_available_locales
    raise I18n::InvalidLocale.new(locale) if !locale_available?(locale)
   end
end

which can be enhanced to be able to handle wrappers that respond to #to_sym, i.e.

def enforce_available_locales!(locale)
  if locale != false && config.enforce_available_locales
    raise I18n::InvalidLocale.new(locale) if !locale_available?(locale.to_sym)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant