Skip to content

Commit 6982d03

Browse files
committed
Eagerly defrost chilled strings
Ref: https://bugs.ruby-lang.org/issues/20205 One minor backward compatibility issue with chilled strings is that since they claim to be frozen, code using the pattern: ```ruby StringIO.new("") ``` Is now producing read only `StringIO` instances. It would be preferable to emit a warning instead. We can detect whether the current Ruby produce chilled strings and if so preemptively attempt to mutate the given string to produce the warning immediately and preserve the original behavior.
1 parent 779f713 commit 6982d03

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

lib/stringio.rb

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
require "stringio.so"
2+
3+
if "test".frozen? && !"test".equal?("test") # Ruby 3.4+ chilled strings
4+
class StringIO
5+
alias_method :_initialize, :initialize
6+
private :_initialize
7+
8+
def initialize(*args, **kwargs)
9+
string = args.first
10+
if string && string.frozen?
11+
begin
12+
string << "" # Eagerly defrost the string
13+
rescue FrozenError
14+
end
15+
end
16+
_initialize(*args, **kwargs)
17+
end
18+
end
19+
end

test/stringio/test_stringio.rb

+8
Original file line numberDiff line numberDiff line change
@@ -981,4 +981,12 @@ def test_coderange_after_overwrite
981981
def assert_string(content, encoding, str, mesg = nil)
982982
assert_equal([content, encoding], [str, str.encoding], mesg)
983983
end
984+
985+
if "test".frozen? && !"test".equal?("test") # Ruby 3.4+ chilled strings
986+
def test_chilled_string
987+
io = StringIO.new("")
988+
io << "test"
989+
assert_equal("test", s.string)
990+
end
991+
end
984992
end

0 commit comments

Comments
 (0)