Class: Rack::FormatResponse

Inherits:
Object
  • Object
show all
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
messagepong

# 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

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)
  [@status, @headers, @body || body]
end