Skip to content

Commit

Permalink
Protocol::HTTP::Body::File should be rewindable?.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Oct 14, 2024
1 parent f564127 commit 0f1fa9d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
10 changes: 10 additions & 0 deletions lib/protocol/http/body/file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def self.open(path, *arguments, **options)

def initialize(file, range = nil, size: file.size, block_size: BLOCK_SIZE)
@file = file
@range = range

@block_size = block_size

Expand All @@ -26,6 +27,7 @@ def initialize(file, range = nil, size: file.size, block_size: BLOCK_SIZE)
@offset = range.min
@length = @remaining = range.size
else
@file.seek(0)
@offset = 0
@length = @remaining = size
end
Expand All @@ -51,11 +53,19 @@ def ready?
true
end

def buffered
self.class.new(@file.dup, @range, block_size: @block_size)
end

def rewind
@file.seek(@offset)
@remaining = @length
end

def rewindable?
true
end

def read
if @remaining > 0
amount = [@remaining, @block_size].min
Expand Down
24 changes: 22 additions & 2 deletions test/protocol/http/body/file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
let(:path) {File.expand_path("file_spec.txt", __dir__)}
let(:body) {subject.open(path)}

after do
@body&.close
end

# with '#stream?' do
# it "should be streamable" do
# expect(body).to be(:stream?)
Expand All @@ -23,11 +27,16 @@

with "#close" do
it "should close file" do
expect(body.file).to receive(:close)

body.close

expect(body).to be(:empty?)
expect(body.file).to be(:closed?)
end
end

with "#rewindable?" do
it "should be rewindable" do
expect(body).to be(:rewindable?)
end
end

Expand All @@ -43,6 +52,17 @@
end
end

with "#buffered" do
it "should return a new instance" do
buffered = body.buffered

expect(buffered).to be_a(Protocol::HTTP::Body::File)
expect(buffered).not.to be_equal(body)
ensure
buffered&.close
end
end

with "#inspect" do
it "generates a string representation" do
expect(body.inspect).to be =~ /Protocol::HTTP::Body::File file=(.*?) offset=\d+ remaining=\d+/
Expand Down

0 comments on commit 0f1fa9d

Please sign in to comment.