From 20f396cc5873e9969e582b68f9eaafd4e0e96216 Mon Sep 17 00:00:00 2001 From: Alexander Glushkov Date: Thu, 24 Aug 2023 12:17:18 +0300 Subject: [PATCH] Support pluralization in I18n messages backend Pass all provided options down to I18n.t method. It will use `:count` option to pluralize the message. en: foo: one: %{count} foo other: %{count} foos I18n.t(:foo, count: 1) #=> 1 foo I18n.t(:foo, count: 1) #=> 2 foos --- lib/dry/schema/messages/i18n.rb | 3 ++- spec/integration/messages/i18n_spec.rb | 36 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/dry/schema/messages/i18n.rb b/lib/dry/schema/messages/i18n.rb index 49e9be541..e13a6483c 100644 --- a/lib/dry/schema/messages/i18n.rb +++ b/lib/dry/schema/messages/i18n.rb @@ -32,7 +32,8 @@ def initialize def get(key, options = EMPTY_HASH) return unless key - result = t.(key, locale: options.fetch(:locale, default_locale)) + options = {locale: default_locale, **options} + result = t.(key, **options) if result.is_a?(Hash) text = result[:text] diff --git a/spec/integration/messages/i18n_spec.rb b/spec/integration/messages/i18n_spec.rb index 441946022..16a95a305 100644 --- a/spec/integration/messages/i18n_spec.rb +++ b/spec/integration/messages/i18n_spec.rb @@ -203,6 +203,42 @@ def store_errors(**errors) expect(meta).to eql(code: 123) end end + + context "with plural message" do + before do + store_errors( + apples: { + one: "single apple", + other: "%{count} apples" + } + ) + end + + it "uses correct variant" do + template, meta = messages[:apples, path: :path, count: 3] + + expect(template.()).to eql("3 apples") + expect(meta).to eql({}) + end + + context "without count" do + it "returns meta" do + template, meta = messages[:apples, path: :path] + + expect(template.()).to eql({ + one: "single apple", + other: "%{count} apples" + }) + + expect(template.(count: 1)).to eql("single apple") + + expect(meta).to eql({ + one: "single apple", + other: "%{count} apples" + }) + end + end + end end context "with dynamic locale" do