샘플
sinatra 4.2.1: Handle Sinatra route return value type boundaries where returning a bare Hash yields Enumerable key-value array pairs under text/html rather than serializing JSON, and returning a status-headers 2-tuple treats the Hash as the response body
검증된 샘플 — gem sinatra 4.2.1: Handle Sinatra route return value type boundaries where returning a bare Hash yields Enumerable key-value array pairs under…
sha256:4e6f5f2571bb3c814be0e5880976fec924aca91858ea0f43ac917eff250e2306
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 2
- 빌드한 서명 키
- 2
선언된 환경
ruby linux x64 ruby ruby bundler
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-17 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-18 |
케이스
HOW- 목표
- Handle Sinatra route return value type boundaries where returning a bare Hash yields Enumerable key-value array pairs under text/html rather than serializing JSON, and returning a status-headers 2-tuple treats the Hash as the response body
- 심벌
-
- Sinatra::Base
- Sinatra::Response
- Sinatra::Base#invoke
- Sinatra::Base#body
- Sinatra::Base#status
- Sinatra::Base#headers
- Sinatra::Base#halt
- 환경
- ruby
- 생성일
- 2026-08-17T01:21:15Z
컨트랙트
- assert a bare Hash returned from a route is treated as an Enumerable body yielding key-value array pairs with text/html rather than serializing to JSON
- assert returning a status integer and a headers Hash in a two-element array pops the Hash as the body and leaves response headers unset
- assert returning a three-element array unpacks the first element as status, the last as body, and the middle as response headers
- assert returning a bare Integer status code sets the HTTP response status and resets the response body to empty
- assert returning an Array of Strings is treated as an Enumerable streaming body with 200 OK because the first element is not an Integer
- assert returning a Symbol is ignored by route dispatch and leaves the response body empty
- assert returning a custom object with only to_s is ignored while an Enumerable defining each streams yielded chunks
- assert calling the body helper and returning nil retains the explicitly set body while returning an Integer wipes it
- assert halt with a status integer and a Hash pops the Hash as the response body with no headers set
파일
- Gemfile
- Gemfile.lock
- NOTES.md
- csx.json
- src/app.rb
- test/contract.rb
소스
source "https://rubygems.org"
# sinatra 4.2.1 closures are pure Ruby and install without a C compiler toolchain
gem "sinatra", "4.2.1"
gem "rack-test", "2.2.0"
gem "minitest", "5.27.0"
GEM
remote: https://rubygems.org/
specs:
base64 (0.3.0)
logger (1.7.0)
minitest (5.27.0)
mustermann (3.1.1)
rack (3.2.7)
rack-protection (4.2.1)
base64 (>= 0.1.0)
logger (>= 1.6.0)
rack (>= 3.0.0, < 4)
rack-session (2.1.2)
base64 (>= 0.1.0)
rack (>= 3.0.0)
rack-test (2.2.0)
rack (>= 1.3)
sinatra (4.2.1)
logger (>= 1.6.0)
mustermann (~> 3.0)
rack (>= 3.0.0, < 4)
rack-protection (= 4.2.1)
rack-session (>= 2.0.0, < 3)
tilt (~> 2.0)
tilt (2.8.0)
PLATFORMS
ruby
x86_64-linux-musl
DEPENDENCIES
minitest (= 5.27.0)
rack-test (= 2.2.0)
sinatra (= 4.2.1)
CHECKSUMS
base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
mustermann (3.1.1) sha256=4c6170c7234d5499c345562ba7c7dfe73e1754286dcc1abb053064d66a127198
rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7
rack-protection (4.2.1) sha256=cf6e2842df8c55f5e4d1a4be015e603e19e9bc3a7178bae58949ccbb58558bac
rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8
rack-test (2.2.0) sha256=005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463
sinatra (4.2.1) sha256=b7aeb9b11d046b552972ade834f1f9be98b185fa8444480688e3627625377080
tilt (2.8.0) sha256=ba472eb2716fe1e04112d6d219a9dae938ec09a6a1e2ad3ecc7922e79bde3721
BUNDLED WITH
4.0.18
# Sinatra Route Return Value Type Boundaries and Tuple Unpacking
## Search Result
The initial lookup returned sample `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b`, which demonstrated running a modular Sinatra 4 app with rack-test in-process, Host authorization filtering, params precedence, and 404 handling. This sample investigates an entirely different boundary: how Sinatra dispatches and unpacks route return values, tuples, Enumerable objects, and explicit helper mutations.
## Failure Mode
When an application returns a bare Hash or a two-element status-headers tuple, the failure is silent with HTTP 200/400 and a green build: Rack iterates `Hash#each` to concatenate key-value Array pairs under `text/html` instead of serializing JSON, and two-element tuples pop the Hash as the body rather than applying headers.
## Mechanism
Sinatra handles route block results inside `Sinatra::Base#invoke`:
```ruby
def invoke(&block)
res = catch(:halt, &block)
res = [res] if (Integer === res) || (String === res)
if (Array === res) && (Integer === res.first)
res = res.dup
status(res.shift)
body(res.pop)
headers(*res)
elsif res.respond_to? :each
body res
end
nil
end
```
1. **Bare Hash return**: `Hash` implements `Enumerable#each`, yielding `[key, value]` pairs. Sinatra assigns the Hash directly to `@response.body`. Downstream Rack handlers iterate the body, stringifying and concatenating each yielded pair (e.g., `"[:id, 101][:status, \"active\"]"`) under the default `text/html;charset=utf-8` header without raising any exception.
2. **Two-element tuple `[status, hash]`**: `res.shift` sets the HTTP status code, and `res.pop` pops the Hash as the response body. The remaining elements passed to `headers(*res)` are empty, leaving the Hash rendered into the body and custom headers unset.
3. **Three-element tuple `[status, headers, body]`**: `res.shift` takes the status, `res.pop` takes the body, and the intermediate Hash is forwarded to `headers(...)`.
4. **Bare Integer**: An Integer return is wrapped in a single-element array `[code]`. `res.shift` sets the status and `res.pop` pops `nil`, explicitly clearing the response body to `""`.
5. **Array of Strings**: When the first element is not an Integer, the Array skips status unpacking and enters `elsif res.respond_to? :each`, streaming chunks directly with HTTP 200.
6. **Symbol and `#to_s` objects**: Types that do not match `Integer`, `String`, `Array` with leading Integer, or `respond_to?(:each)` are ignored by `invoke`, leaving the response body empty.
{"case":{"believed":"Returning a Ruby Hash from a Sinatra route block either serializes to JSON or raises a type error, and returning a two-element array of a status integer and a hash sets the response status and headers.","caseId":"case:sha256:6b252b46c79610f239c19f3205eefcb458aedf8a7ab7ca9a6c825ad310e578fe","contract":["assert a bare Hash returned from a route is treated as an Enumerable body yielding key-value array pairs with text/html rather than serializing to JSON","assert returning a status integer and a headers Hash in a two-element array pops the Hash as the body and leaves response headers unset","assert returning a three-element array unpacks the first element as status, the last as body, and the middle as response headers","assert returning a bare Integer status code sets the HTTP response status and resets the response body to empty","assert returning an Array of Strings is treated as an Enumerable streaming body with 200 OK because the first element is not an Integer","assert returning a Symbol is ignored by route dispatch and leaves the response body empty","assert returning a custom object with only to_s is ignored while an Enumerable defining each streams yielded chunks","assert calling the body helper and returning nil retains the explicitly set body while returning an Integer wipes it","assert halt with a status integer and a Hash pops the Hash as the response body with no headers set"],"goal":"Handle Sinatra route return value type boundaries where returning a bare Hash yields Enumerable key-value array pairs under text/html rather than serializing JSON, and returning a status-headers 2-tuple treats the Hash as the response body","kind":"HOW","packages":["pkg:gem/sinatra@4.2.1","pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7","pkg:gem/mustermann@3.1.1","pkg:gem/tilt@2.8.0"],"schemaVersion":1,"symbols":["Sinatra::Base","Sinatra::Response","Sinatra::Base#invoke","Sinatra::Base#body","Sinatra::Base#status","Sinatra::Base#headers","Sinatra::Base#halt"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/sinatra@4.2.1","pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7","pkg:gem/mustermann@3.1.1","pkg:gem/tilt@2.8.0"],"schemaVersion":1,"symbols":["Sinatra::Base","Sinatra::Response","Sinatra::Base#invoke","Sinatra::Base#body","Sinatra::Base#status","Sinatra::Base#headers","Sinatra::Base#halt"],"verifierAdapter":"rubygems@1"}
require "sinatra/base"
# Custom object providing only to_s (not Enumerable, not String, not Integer)
class DisplayName
def initialize(name)
@name = name
end
def to_s
@name
end
end
# Custom Enumerable response body yielding chunked strings
class ChunkedStream
def initialize(chunks)
@chunks = chunks
end
def each(&block)
@chunks.each(&block)
end
end
class ReturnTypeApp < Sinatra::Base
# Disable host authorization in development mode so rack-test requests pass freely
set :host_authorization, permitted_hosts: []
set :show_exceptions, false
set :raise_errors, true
# 1. Returning a bare Hash from a route
get "/return/bare-hash" do
{ id: 101, status: "active" }
end
# 2. Returning a bare Integer status code
get "/return/integer-204" do
204
end
get "/return/integer-200" do
200
end
# 3. Returning a 2-element array [status, hash]
get "/return/status-and-hash" do
[400, { "Content-Type" => "application/json" }]
end
# 4. Returning a 3-element array [status, headers, body]
get "/return/status-headers-body" do
[201, { "X-Custom-Header" => "registered" }, '{"status":"created"}']
end
# 5. Returning an Array of Strings (first element is not an Integer)
get "/return/string-array" do
["chunk-alpha-", "chunk-beta"]
end
# 6. Returning a Symbol
get "/return/symbol" do
:some_symbol_value
end
# 7. Returning an object defining only #to_s
get "/return/custom-to-s" do
DisplayName.new("alice")
end
# 8. Returning an Enumerable defining #each
get "/return/custom-enumerable" do
ChunkedStream.new(["stream-part-1\n", "stream-part-2\n"])
end
# 9. Calling body helper then returning nil vs returning an Integer
get "/override/body-then-nil" do
body "explicitly set body"
nil
end
get "/override/body-then-int" do
body "explicitly set body"
204
end
# 10. Halt with 2 elements vs 3 elements
get "/halt/status-and-hash" do
halt 422, { error: "unprocessable" }
end
get "/halt/status-headers-body" do
halt 422, { "Content-Type" => "application/json" }, '{"error":"unprocessable"}'
end
end
require "minitest/autorun"
require "rack/test"
require_relative "../src/app"
class SinatraReturnTypeContract < Minitest::Test
include Rack::Test::Methods
def app
ReturnTypeApp
end
def test_a_bare_hash_is_treated_as_an_enumerable_body_yielding_array_pairs
# A competent developer or model expects returning a Ruby Hash from a route
# to either serialize to JSON or raise a type error.
# Instead, Hash implements Enumerable#each yielding [key, value] pairs.
# Sinatra assigns the Hash directly to @response.body, and Rack concatenates
# the yielded Array pairs via to_s under the default text/html content type.
get "/return/bare-hash"
assert_equal 200, last_response.status
assert_equal "[:id, 101][:status, \"active\"]", last_response.body
assert_equal "text/html;charset=utf-8", last_response.content_type
refute_equal "application/json", last_response.content_type
end
def test_a_two_element_array_pops_the_hash_as_the_body_and_leaves_headers_empty
# In [status, payload], Sinatra's invoke method uses res.shift for status
# and res.pop for body, passing remaining elements to headers(*res).
# When length is 2, the second element is ALWAYS popped as the body,
# so a Hash intended as headers becomes the body and headers remain unset.
get "/return/status-and-hash"
assert_equal 400, last_response.status
assert_equal "[\"Content-Type\", \"application/json\"]", last_response.body
assert_equal "text/html;charset=utf-8", last_response.content_type
refute_equal "application/json", last_response.content_type
end
def test_a_three_element_array_unpacks_status_headers_and_body
# With 3 elements, shift extracts status, pop extracts body, and the
# middle Hash is passed to headers(*res).
get "/return/status-headers-body"
assert_equal 201, last_response.status
assert_equal "registered", last_response.headers["x-custom-header"]
assert_equal '{"status":"created"}', last_response.body
end
def test_a_bare_integer_sets_the_response_status_and_clears_the_body
# Returning an Integer wraps it in [code], shifts status(code), and pops
# body(nil) which resets the body to empty.
get "/return/integer-204"
assert_equal 204, last_response.status
assert_equal "", last_response.body
get "/return/integer-200"
assert_equal 200, last_response.status
assert_equal "", last_response.body
end
def test_a_string_array_is_treated_as_a_streaming_body_not_a_status_tuple
# Sinatra checks (Array === res) && (Integer === res.first).
# When the first element is a String, it skips status parsing and treats
# the entire Array as an Enumerable body with status 200.
get "/return/string-array"
assert_equal 200, last_response.status
assert_equal "chunk-alpha-chunk-beta", last_response.body
end
def test_a_symbol_return_is_ignored_by_dispatch_leaving_an_empty_body
# Symbol is neither Integer, String, Array with leading Integer, nor Enumerable.
# Sinatra's invoke method ignores it, resulting in status 200 and an empty body.
get "/return/symbol"
assert_equal 200, last_response.status
assert_equal "", last_response.body
end
def test_a_custom_object_with_to_s_is_ignored_while_enumerable_each_streams
# Sinatra does not call to_s on route return values; it checks respond_to?(:each).
# An object with only to_s produces an empty body, whereas an Enumerable streams.
get "/return/custom-to-s"
assert_equal 200, last_response.status
assert_equal "", last_response.body
get "/return/custom-enumerable"
assert_equal 200, last_response.status
assert_equal "stream-part-1\nstream-part-2\n", last_response.body
end
def test_returning_nil_preserves_explicit_body_while_returning_an_int_wipes_it
# Returning nil does not match any branch in invoke, preserving earlier body calls.
# Returning an Integer pops nil for body, wiping any previously set body.
get "/override/body-then-nil"
assert_equal 200, last_response.status
assert_equal "explicitly set body", last_response.body
get "/override/body-then-int"
assert_equal 204, last_response.status
assert_equal "", last_response.body
end
def test_halt_shares_the_same_tuple_shift_pop_unpacking_behavior
# halt throws arguments caught by invoke, undergoing identical shift/pop unpacking.
# halt 422, { error: "unprocessable" } sets the Hash as the body.
get "/halt/status-and-hash"
assert_equal 422, last_response.status
assert_equal "[:error, \"unprocessable\"]", last_response.body
get "/halt/status-headers-body"
assert_equal 422, last_response.status
assert_equal "application/json", last_response.content_type
assert_equal '{"error":"unprocessable"}', last_response.body
end
end