From be2f3a056a964f855def08a1e84a7afe5d0c46db Mon Sep 17 00:00:00 2001 From: fatkodima Date: Fri, 17 Feb 2023 16:13:17 +0200 Subject: [PATCH] Return same string object when no interpolations were made --- lib/i18n/interpolate/ruby.rb | 8 +++++++- test/i18n/interpolate_test.rb | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/i18n/interpolate/ruby.rb b/lib/i18n/interpolate/ruby.rb index bfe484e8..5b50593f 100644 --- a/lib/i18n/interpolate/ruby.rb +++ b/lib/i18n/interpolate/ruby.rb @@ -28,7 +28,11 @@ def interpolate(string, values) def interpolate_hash(string, values) pattern = INTERPOLATION_PATTERNS_CACHE[config.interpolation_patterns] - string.gsub(pattern) do |match| + interpolated = false + + interpolated_string = string.gsub(pattern) do |match| + interpolated = true + if match == '%%' '%' else @@ -42,6 +46,8 @@ def interpolate_hash(string, values) $3 ? sprintf("%#{$3}", value) : value end end + + interpolated ? interpolated_string : string end end end diff --git a/test/i18n/interpolate_test.rb b/test/i18n/interpolate_test.rb index 79e59a99..2d54090f 100644 --- a/test/i18n/interpolate_test.rb +++ b/test/i18n/interpolate_test.rb @@ -65,9 +65,15 @@ def gsub(*args, &block) end end + test "with String subclass that redefined gsub method" do assert_equal "Hello mars world", I18n.interpolate(RailsSafeBuffer.new("Hello %{planet} world"), :planet => 'mars') end + + test "with String subclass that redefined gsub method returns same object if no interpolations" do + string = RailsSafeBuffer.new("Hello world") + assert_same string, I18n.interpolate(string, :planet => 'mars') + end end class I18nMissingInterpolationCustomHandlerTest < I18n::TestCase