Skip to content

Commit

Permalink
Support BodyProxy#to_ary if body responds to to_ary
Browse files Browse the repository at this point in the history
Call BodyProxy#close if BodyProxy#to_ary is called.
  • Loading branch information
jeremyevans committed Mar 19, 2023
1 parent 413989d commit 42c50a7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
10 changes: 8 additions & 2 deletions lib/rack/body_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def initialize(body, &block)
# Return whether the wrapped body responds to the method.
def respond_to_missing?(method_name, include_all = false)
case method_name
when :to_str, :to_ary
when :to_str
false
else
super or @body.respond_to?(method_name, include_all)
Expand Down Expand Up @@ -44,8 +44,14 @@ def closed?
# Delegate missing methods to the wrapped body.
def method_missing(method_name, *args, &block)
case method_name
when :to_str, :to_ary
when :to_str
super
when :to_ary
begin
@body.__send__(method_name, *args, &block)
ensure
close
end
else
@body.__send__(method_name, *args, &block)
end
Expand Down
13 changes: 11 additions & 2 deletions test/spec_body_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,17 @@ def body.banana(foo: nil); foo end
proxy.banana(foo: 1).must_equal 1
end

it 'not respond to :to_ary' do
proxy = Rack::BodyProxy.new([]) { }
it 'respond to :to_ary if body does responds to it, and have to_ary call close' do
proxy_closed = false
proxy = Rack::BodyProxy.new([]) { proxy_closed = true }
proxy.respond_to?(:to_ary).must_equal true
proxy_closed.must_equal false
proxy.to_ary.must_equal []
proxy_closed.must_equal true
end

it 'not respond to :to_ary if body does not respond to it' do
proxy = Rack::BodyProxy.new([].map) { }
proxy.respond_to?(:to_ary).must_equal false
proc do
proxy.to_ary
Expand Down

0 comments on commit 42c50a7

Please sign in to comment.