Skip to content

Commit 98d8acf

Browse files
samuel-williams-shopifyioquatix
authored andcommitted
Head.for(nil) -> nil.
1 parent fd9d606 commit 98d8acf

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

lib/protocol/http/body/head.rb

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,24 @@ module Body
1212
# Represents a body suitable for HEAD requests, in other words, a body that is empty and has a known length.
1313
class Head < Readable
1414
# Create a head body for the given body, capturing its length and then closing it.
15-
def self.for(body)
16-
head = self.new(body.length)
17-
18-
body.close
15+
#
16+
# If a body is provided, the length is determined from the body, and the body is closed.
17+
# If no body is provided, and the content length is provided, a head body is created with that length.
18+
# This is useful for creating a head body when you only know the content length but not the actual body, which may happen in adapters for HTTP applications where the application may not provide a body for HEAD requests, but the content length is known.
19+
#
20+
# @parameter body [Readable | Nil] the body to create a head for.
21+
# @parameter content_length [Integer | Nil] the content length of the body, if known.
22+
# @returns [Head | Nil] the head body, or nil if the body is nil.
23+
def self.for(body, content_length = nil)
24+
if body
25+
head = self.new(body.length)
26+
body.close
27+
return head
28+
elsif content_length
29+
return self.new(content_length)
30+
end
1931

20-
return head
32+
return nil
2133
end
2234

2335
# Initialize the head body with the given length.

test/protocol/http/body/head.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,21 @@
5555
expect(body).to have_attributes(length: be == 1)
5656
body.close
5757
end
58+
59+
it "uses the content length if no body is provided" do
60+
content_length = 42
61+
head_body = subject.for(nil, content_length)
62+
63+
expect(head_body).to have_attributes(length: be == content_length)
64+
expect(head_body).to be(:empty?)
65+
expect(head_body).to be(:ready?)
66+
end
67+
end
68+
69+
with ".for with nil body" do
70+
it "returns nil when body is nil" do
71+
body = subject.for(nil)
72+
expect(body).to be_nil
73+
end
5874
end
5975
end

0 commit comments

Comments
 (0)