Class: Rack::JSON

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/json.rb

Constant Summary collapse

APPLICATION_JSON =
'application/json'.freeze
FORM_HASH =
'rack.request.form_hash'.freeze
FORM_INPUT =
'rack.request.form_input'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JSON

Returns a new instance of JSON.



26
27
28
# File 'lib/rack/json.rb', line 26

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rack/json.rb', line 30

def call(env)
  request = Rack::Request.new env

  if request.media_type == APPLICATION_JSON && !(body = request.body.read).empty?
    request.body.rewind
    parsed = parse_json body
    parsed = {'_json' => parsed} unless parsed.is_a? Hash

    env.update FORM_HASH  => parsed, FORM_INPUT => request.body
  end

  @app.call env

rescue json_parser_error_class => e
  on_parse_error e
end

#json_parser_error_classObject

Override to use a different parser



16
17
18
# File 'lib/rack/json.rb', line 16

def json_parser_error_class
  ::JSON::ParserError
end

#on_parse_error(e) ⇒ Object

Override for different error behavior



21
22
23
24
# File 'lib/rack/json.rb', line 21

def on_parse_error(e)
  message = "Invalid JSON"
  [400, {'Content-Length' => message.length}, [message]]
end

#parse_json(json) ⇒ Object

Override to use a different parser



11
12
13
# File 'lib/rack/json.rb', line 11

def parse_json(json)
  ::JSON.parse(json, :create_additions => false)
end