Reputation: 905
i have a question on how to make proper of use the Rack::Response-Object in a server-response.
In line 711
the method Rack::Lint#each
(https://github.com/rack/rack/blob/master/lib/rack/lint.rb#L711) asserts among others that part.kind_of? String
such that assert("Body yielded non-string value #{part.inspect}")
The most basic response is a triplet like
[status, headers, body]
I got an error message, when I put the Rack::Response
-Object in the triplet like that:
[status, headers, rs]
where rs is the Response-Object.
I got it to work with
[status, headers, st.body]
however, as it then passes the above-mentioned assertion !
My question is only if this makes correct use of Rack::Response
, or if not, what are then the proper ways of using it in a Server-Response.
Thank you very much
Upvotes: 1
Views: 2377
Reputation: 15967
Rack::Response
is simply an interface that is new'd up with 3 arguments, the body, the status code and the headers.
The body argument can either respond to #to_str
or it must implement #each
and whatever is yielded to #each
must respond to #to_s
.
So as a straightforward answer consider this to be valid:
response = Rack::Response.new(
['a','series', 'of', 'strings'],
200,
{ 'Content-Type' => 'application/json' }
)
This is valid as well
response = Rack::Response.new(
'{}',
200,
{ 'Content-Type' => 'application/json' }
)
Or if you have a custom class that say is proxying a response from an API, this would also suffice:
class ApiClient
def initialize
@response = get_something
end
def each
@response.chars.each { |el| yield el }
end
private
def get_something
"a string of responses"
end
end
response = Rack::Response.new(
ApiClient.new,
200,
{ 'Content-Type' => 'application/json' }
)
When you're ready to return your response object back to the caller, you simply called #finish
on your Rack::Response
instance. This is also aliased as #to_a
and #to_ary
.
Upvotes: 3