Class: Waw::JSONController

Inherits:
Object show all
Includes:
Rack::Delegator
Defined in:
lib/waw/controllers/json_controller.rb

Overview

Decorates a given controller and convert result as JSON unless stated otherwise.

Instance Method Summary collapse

Methods included from Rack::Delegator

#_visit, #delegate, #find_rack_app, #find_url_of, #has_delegate?, #is_delegate?, #visit

Constructor Details

#initialize(app) ⇒ JSONController

Creates a controller instance

Raises:

  • (WAWError)


11
12
13
14
# File 'lib/waw/controllers/json_controller.rb', line 11

def initialize(app)
  raise WAWError, "JSONController expects a delegation controller" if app.nil?
  @app = app
end

Instance Method Details

#call(env) ⇒ Object

Calls the delegation controller and encode its result in JSON



17
18
19
20
21
22
23
# File 'lib/waw/controllers/json_controller.rb', line 17

def call(env)
  status, headers, body = @app.call(env)
  header = {} if headers.nil?
  headers['Content-Type'] = 'application/json' if headers['Content-Type'].nil? 
  body = ::JSON.generate(body) if json_response?(headers)
  [status, headers, body]
end

#json_response?(headers) ⇒ Boolean

Do i need to encode as JSON?

Returns:



26
27
28
# File 'lib/waw/controllers/json_controller.rb', line 26

def json_response?(headers)
  (headers['Content-Type'] == 'application/json')
end