FIX: Validate MF strings when adding overrides

Currently, when adding translation overrides, values aren’t validated
for MF strings. This results in being able to add invalid plural keys or
even strings containing invalid syntax.

This patch addresses this issue by compiling the string when saving an
override if the key is detected as an MF one.

If there’s an error from the compiler, it’s added to the model errors,
which in turn is displayed to the user in the admin UI, helping them to
understand what went wrong.
This commit is contained in:
Loïc Guitaut
2024-07-25 16:56:08 +02:00
committed by Loïc Guitaut
parent f169985fce
commit 53210841c8
3 changed files with 64 additions and 13 deletions

View File

@ -148,6 +148,32 @@ RSpec.describe TranslationOverride do
end
end
end
describe "MessageFormat translations" do
subject(:override) do
described_class.new(
translation_key: "admin_js.admin.user.delete_all_posts_confirm_MF",
locale: "en",
)
end
it do
is_expected.to allow_value(
"This has {COUNT, plural, one{one member} other{# members}}.",
).for(:value).against(:base)
end
it do
is_expected.not_to allow_value(
"This has {COUNT, plural, one{one member} many{# members} other{# members}}.",
).for(:value).with_message(/plural case many is not valid/, against: :base)
end
it do
is_expected.not_to allow_value("This has {COUNT, ").for(:value).with_message(
/invalid syntax/,
against: :base,
)
end
end
end
it "upserts values" do
@ -340,4 +366,20 @@ RSpec.describe TranslationOverride do
expect(translation.invalid_interpolation_keys).to contain_exactly("foo")
end
end
describe "#message_format?" do
subject(:override) { described_class.new(translation_key: key) }
context "when override is for a MessageFormat translation" do
let(:key) { "admin_js.admin.user.delete_all_posts_confirm_MF" }
it { is_expected.to be_a_message_format }
end
context "when override is not for a MessageFormat translation" do
let(:key) { "admin_js.type_to_filter" }
it { is_expected.not_to be_a_message_format }
end
end
end