Skip to content

Commit

Permalink
Fix SanitizedFile#read to behave in the same way with IO#read with ar…
Browse files Browse the repository at this point in the history
…guments

Fixes #2770
  • Loading branch information
mshibuya committed Dec 31, 2024
1 parent ce0aee8 commit 9eace1c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 deletions.
33 changes: 22 additions & 11 deletions lib/carrierwave/sanitized_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,24 +129,35 @@ def exists?
# [String] contents of the file
#
def read(*args)
if @content
if args.empty?
if args.empty?
if @content
@content
elsif is_path?
File.open(@file, "rb") {|file| file.read }
else
length, outbuf = args
raise ArgumentError, "outbuf argument not supported since the content is already loaded" if outbuf
@content[0, length]
@file.try(:rewind)
@content = @file.read
@file.try(:close) unless @file.class.ancestors.include?(::StringIO) || @file.try(:closed?)
@content
end
elsif is_path?
File.open(@file, "rb") {|file| file.read(*args)}
else
@file.try(:rewind)
@content = @file.read(*args)
@file.try(:close) unless @file.class.ancestors.include?(::StringIO) || @file.try(:closed?)
@content
if is_path?
@file = File.open(path, "rb")
elsif @file.is_a?(CarrierWave::Uploader::Base)
@file = StringIO.new(@file.read)
end

@file.read(*args)
end
end

##
# Rewinds the underlying file.
#
def rewind
@file.rewind if @file.respond_to?(:rewind)
end

##
# Moves the file to the given path
#
Expand Down
17 changes: 16 additions & 1 deletion spec/sanitized_file_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,22 @@
end

it "always reads from the file if arguments are given" do
sanitized_file.read
sanitized_file.read(0)
expect(sanitized_file.file).to receive(:read).with(4).and_call_original
expect(sanitized_file.read(4)).to eq("this")
end

it "properly emulates the behavior of IO#read" do
expect(sanitized_file.read(4)).to eq("this")
expect(sanitized_file.read(10)).to eq(" is stuff")
expect(sanitized_file.read(1)).to be_nil
end
end

describe "#rewind" do
it "rewinds the underlying file" do
sanitized_file.read(5)
sanitized_file.rewind
expect(sanitized_file.read(4)).to eq("this")
end
end
Expand Down

0 comments on commit 9eace1c

Please sign in to comment.