brainspec / enumerize

Enumerated attributes with I18n and ActiveRecord/Mongoid support
MIT License
1.72k stars 190 forks source link

Reuse model translations in i18n_scope #406

Closed Timmitry closed 1 year ago

Timmitry commented 2 years ago

Background

In a Rails app, we typicall have model translations like this:

en:
  activerecord:
    models:
      article:
        one: Article
        other: Articles

When using polymorphic relations, e.g. when specifying a Rating model which either references an Article or a Comment, via a belongs_to :rateable, polymorphic: true, we would have a rateable_id and rateably_type column.

I like to use enumerize to validate my rateably_type column, via enumerize :rateably_type, in: %w[Article Comment], which works as intended.

Now, if I were to display a list of all ratings, I would do something like this:

<% ratings.each do |rating| %>
  = rating.rateable_type.text
<% end %>

Where rateably_type.text (or rateable_type_text) would give me the translated enumerize value. This is usually taken from en.enumerize.rating.rateably_type.<value>, where value would be Article or Comment.

Problem

The translations I specify for enumerize are the same translations I already stored under activerecord.models.article. I don't like repetition, so I'm looking for a way to avoid this 🙂

There is the i18n_scope-Option which can be used in the Model, where I could do enumerize :rateably_type in: %w[Article Comment], i18n_scope: "activerecord.models".

However, this does not work, as the model translations use one and other. So when using rating.rateable_type.text, it gives me { one: "Article", other: "Articles" } instead of just "Article".

Proposed solutions

  1. Allow passing a proc to i18n_scope, which gets evaluated: i18n_scope: ->(value) { I18n.t(value, scope: "activerecord.models", count: 1 }
  2. Allow passing arguments to the .text or *_text-methods: rating.rateable_type.text(count: 1)

Number 1 would be my favourite, as it gives the most flexibility 🙂

Let me know how you think about that issue - I can probably make a PR if that contribution would be welcome, but wanted to check first!

nashby commented 2 years ago

Hey @Timmitry! Making i18n_scope to accept procs sounds good to me, feel free to send a PR!

nashby commented 1 year ago

@Timmitry hey! I've just added it to master. Could you please test it?