Class: Rack::ParsePostedJSON
- Inherits:
-
Object
- Object
- Rack::ParsePostedJSON
- Defined in:
- lib/rack-parse-posted-json.rb
Constant Summary collapse
- METHODS_WITH_BODY =
['POST', 'PUT']
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ ParsePostedJSON
constructor
A new instance of ParsePostedJSON.
Constructor Details
#initialize(app) ⇒ ParsePostedJSON
Returns a new instance of ParsePostedJSON.
5 6 7 |
# File 'lib/rack-parse-posted-json.rb', line 5 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/rack-parse-posted-json.rb', line 9 def call(env) begin if METHODS_WITH_BODY.include?(env['REQUEST_METHOD']) data = env['rack.input'].read data.force_encoding('utf-8') env['json'] = JSON.parse(data) end rescue JSON::ParserError => error body = {message: error.}.to_json headers = { 'Content-Type' => 'application/json', 'Content-Length' => body.bytesize.to_s } return [400, headers, [body]] end @app.call(env) end |