Commit ab7b390
committed
Allow response_body_formatter config to format "binary" responses
Following this issue on Rack's repository:
[Fix incorrect MockResponse#body String encoding](rack/rack#1486), it looks like we can expect, from now on, that Rack's `response_body` encoding will be `Encoding::ASCII_8BIT`:
> I think the response body should probably always be ASCII-8BIT. Rack
can't really know anything about the encoding of the bytes that users
want to send. At the end of the day, it's just bytes written to the
socket, and I don't think Rack should have any opinion about the
encoding the user sends.
Therefore, `rspec_api_documentation` cannot rely on
`response_body.encoding` to determine whether the response is binary
data or not. This line becomes incorrect:
https://github.com/zipmark/rspec_api_documentation/blob/81e5c563ce6787f143cf775c64e2bd08c35d3585/lib/rspec_api_documentation/client_base.rb#L90-L91
The real fix would be to figure out a better way to define whether a
string is binary or not, but I believe this is a bit outside the scope of my
knowledge.
In this PR, I'm focusing on giving any application using the
`rspec_api_documentation` the choice on how to process the
response_body, and particularly on how to detect binary data, while not
altering `rspec_api_documentation`'s default behaviour.
As an additional benefit, this change would allow an application to
display friendlier responses in the documentation for some binary types.
For example, PNG data:
```rb
Proc.new do |content_type, response_body|
# http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature
if response_body[0,8] == "\x89PNG\r\n\u001A\n"
"<img src=\"data:image/png;base64,#{Base64.strict_encode64(response_body)}\" />"
elsif content_type =~ /application\/.*json/
JSON.pretty_generate(JSON.parse(response_body))
else
response_body
end
end
```1 parent 81e5c56 commit ab7b390
File tree
3 files changed
+8
-8
lines changed- lib/rspec_api_documentation
3 files changed
+8
-8
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
250 | 250 | | |
251 | 251 | | |
252 | 252 | | |
253 | | - | |
| 253 | + | |
| 254 | + | |
254 | 255 | | |
255 | 256 | | |
256 | 257 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
87 | 87 | | |
88 | 88 | | |
89 | 89 | | |
90 | | - | |
91 | | - | |
92 | | - | |
93 | | - | |
94 | | - | |
95 | | - | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
96 | 93 | | |
97 | 94 | | |
98 | 95 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
118 | 118 | | |
119 | 119 | | |
120 | 120 | | |
121 | | - | |
| 121 | + | |
| 122 | + | |
| 123 | + | |
122 | 124 | | |
123 | 125 | | |
124 | 126 | | |
| |||
0 commit comments