Class: Rack::FormatResponse
- Inherits:
-
Object
- Object
- Rack::FormatResponse
- Defined in:
- lib/rack/format_response.rb
Overview
A Rack middleware for automatically formatting response body
e.g.
# in usual case
get "/ping" do
{"message"=>"pong"}
end
->
# forced to to_s
# use Rack::FormatResponse # with string response
get "/ping" do
"pong"
end
->
# calls Rack::FormatResponse#format_string that effects nothing
# in short, nothing special
Content-Type: text/html
"pong"
# use Rack::FormatResponse # with hash response
get "/ping" do
{"message"=>"pong"}
end
->
# calls Rack::FormatResponse#format_hash_to_json
# due to Rack::FormatResponse::MAPPINGS
Content-Type: application/json;charset=utf-8
{"message":"pong"}
Defined Under Namespace
Classes: InvalidFormat, UnknownFormat
Constant Summary collapse
- MAPPINGS =
{ "Hash" => :format_hash_to_json, }
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, opts = {}) ⇒ FormatResponse
constructor
A new instance of FormatResponse.
Constructor Details
#initialize(app, opts = {}) ⇒ FormatResponse
Returns a new instance of FormatResponse.
44 45 46 47 |
# File 'lib/rack/format_response.rb', line 44 def initialize(app, opts = {}) @app = app @opts = opts end |
Instance Method Details
#call(env) ⇒ Object
49 50 51 52 53 |
# File 'lib/rack/format_response.rb', line 49 def call(env) @status, @headers, body = @app.call(env) body = [apply(body)].flatten [@status, @headers, @body || body] end |