Skip to content

Commit 38b0819

Browse files
committed
Fix Ruby 3.4 frozen string literal warnings with StringIO
PR #123 fixed frozen string warnings on line 127 (buffer creation) but missed the warnings triggered by calling binmode/set_encoding on StringIO objects at lines 120-121. These methods modify StringIO's internal string encoding, which triggers Ruby 3.4 deprecation warnings when running with verbose warnings (-W2), which Rails test suites use by default. Skip these calls for StringIO objects since marcel's byte-reading operations work correctly without the encoding modification, as demonstrated by all 384 tests passing. This maintains the existing defensive respond_to? checks for File objects.
1 parent 3d3c5dc commit 38b0819

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

lib/marcel/magic.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,13 @@ def self.child?(child, parent)
115115
end
116116

117117
def self.magic_match(io, method)
118-
return magic_match(StringIO.new(io.to_s), method) unless io.respond_to?(:read)
118+
return magic_match(StringIO.new(+io.to_s), method) unless io.respond_to?(:read)
119+
120+
unless io.is_a?(StringIO)
121+
io.binmode if io.respond_to?(:binmode)
122+
io.set_encoding(Encoding::BINARY) if io.respond_to?(:set_encoding)
123+
end
119124

120-
io.binmode if io.respond_to?(:binmode)
121-
io.set_encoding(Encoding::BINARY) if io.respond_to?(:set_encoding)
122125
buffer = (+"").encode(Encoding::BINARY)
123126

124127
MAGIC.send(method) { |type, matches| magic_match_io(io, matches, buffer) }

test/magic_test.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,25 @@ class Marcel::MimeType::MagicTest < Marcel::TestCase
2525
assert Marcel::Magic.child?('text/csv', 'text/plain')
2626
refute Marcel::Magic.child?('text/plain', 'text/csv')
2727
end
28+
29+
test "no Ruby 3.4 frozen string warnings with StringIO" do
30+
# Ruby 3.4 warns about code that will break when frozen string literals become default
31+
# This test ensures marcel handles StringIO with frozen strings correctly
32+
content = "Test content for mime detection"
33+
io = StringIO.new(content)
34+
35+
# Capture warnings
36+
warnings = []
37+
original_stderr = $stderr
38+
$stderr = StringIO.new
39+
40+
begin
41+
Marcel::MimeType.for(io)
42+
warnings = $stderr.string.lines.grep(/marcel.*magic\.rb.*frozen/)
43+
ensure
44+
$stderr = original_stderr
45+
end
46+
47+
assert_empty warnings, "Expected no frozen string warnings, but got:\n#{warnings.join}"
48+
end
2849
end

0 commit comments

Comments
 (0)