Skip to content

Commit d9e3839

Browse files
committed
Fix String#mb_chars to never mutate the original String
Fix: rails#54076 If we have to call `force_encoding`, we should dup the argument regardless of wheter it is frozen or not as not not mutate our arguments.
1 parent 09e355b commit d9e3839

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

activesupport/lib/active_support/multibyte/chars.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,10 @@ class Chars
5555
# Creates a new Chars instance by wrapping _string_.
5656
def initialize(string)
5757
@wrapped_string = string
58-
@wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
58+
if string.encoding != Encoding::UTF_8
59+
@wrapped_string = @wrapped_string.dup
60+
@wrapped_string.force_encoding(Encoding::UTF_8)
61+
end
5962
end
6063

6164
# Forward all undefined methods to the wrapped string.

activesupport/test/multibyte_test_helpers.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
# frozen_string_literal: true
22

33
module MultibyteTestHelpers
4-
UNICODE_STRING = "こにちわ"
5-
ASCII_STRING = "ohayo"
6-
BYTE_STRING = (+"\270\236\010\210\245").force_encoding("ASCII-8BIT").freeze
4+
# We use Symbol#to_s to create these strings so warnings are emitted if they are mutated
5+
UNICODE_STRING = :"こにちわ".to_s
6+
ASCII_STRING = :"ohayo".to_s
7+
BYTE_STRING = "\270\236\010\210\245".b.freeze
78

89
def chars(str)
910
ActiveSupport::Multibyte::Chars.new(str)

0 commit comments

Comments
 (0)