Skip to content

Commit

Permalink
Support pluralization in I18n messages backend
Browse files Browse the repository at this point in the history
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
  • Loading branch information
cutalion committed Aug 24, 2023
1 parent 3613f98 commit 1f8a52f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/dry/schema/messages/i18n.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
36 changes: 36 additions & 0 deletions spec/integration/messages/i18n_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 1f8a52f

Please sign in to comment.