Skip to content

Commit

Permalink
Do not write non-String to response body when using custom_block_resu…
Browse files Browse the repository at this point in the history
…lts plugin

Previously, the plugin would write non-nil/false values to the
response body, which is not supported unless the value is a
String.  Have unsupported_block_result return nil unless the
return value of the block is a string.
  • Loading branch information
jeremyevans committed Dec 2, 2024
1 parent 711460e commit bfa0e0c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
= master

* Do not write non-String to response body when using custom_block_results plugin (jeremyevans)

= 3.86.0 (2024-11-12)

* Add conditional_sessions plugin, for using the sessions plugin for only a subset of requests (jeremyevans)
Expand Down
21 changes: 19 additions & 2 deletions lib/roda/plugins/custom_block_results.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,16 @@ module RodaPlugins
#
# Note that custom block result handling only occurs if the types
# are not handled by Roda itself. You cannot use this to modify
# the handling of nil, false, or string results.
# the handling of nil, false, or string results. Additionally,
# if the response body has already been written to before the the
# route block exits, then the result of the block is ignored,
# and the related +handle_block_result+ block will not be called
# (this is standard Roda behavior).
#
# The return value of the +handle_block_result+ block is written
# to the body if the block return value is a String, similar to
# standard Roda handling of block results. Non-String return
# values are ignored.
module CustomBlockResults
def self.configure(app)
app.opts[:custom_block_results] ||= {}
Expand All @@ -55,7 +64,15 @@ module RequestMethods
# to get the block result.
def unsupported_block_result(result)
roda_class.opts[:custom_block_results].each do |klass, meth|
return scope.send(meth, result) if klass === result
if klass === result
result = scope.send(meth, result)

if String === result
return result
else
return
end
end
end

super
Expand Down
10 changes: 10 additions & 0 deletions spec/plugin/custom_block_results_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@
end
end

it "should handle blocks that do not return strings" do
2.times do
@app.handle_block_result(Symbol) do |s|
response.status = 201
end
status.must_equal 201
body.must_be_empty
end
end

it "should handle other objects supporting ===" do
@app.handle_block_result(/sy/) do |s|
"x#{s}"
Expand Down

0 comments on commit bfa0e0c

Please sign in to comment.