Class: Goliath::Rack::Render

Inherits:
Object
  • Object
show all
Includes:
Rack::RespondTo
Defined in:
lib/goliath/rack/render.rb

Overview

The render middleware will set the Content-Type of the response based on the provided HTTP_ACCEPT headers.

Examples:

use Goliath::Rack::Render

Instance Method Summary (collapse)

Constructor Details

- (Render) initialize(app, types = nil)

A new instance of Render



15
16
17
18
# File 'lib/goliath/rack/render.rb', line 15

def initialize(app, types = nil)
  @app = app
  ::Rack::RespondTo.media_types = [types].flatten if types
end

Instance Method Details

- (Object) call(env)



20
21
22
23
24
25
26
27
28
29
# File 'lib/goliath/rack/render.rb', line 20

def call(env)
  async_cb = env['async.callback']

  env['async.callback'] = Proc.new do |status, headers, body|
    async_cb.call(post_process(env, status, headers, body))
  end

  status, headers, body = @app.call(env)
  post_process(env, status, headers, body)
end

- (Object) get_content_type(env)



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/goliath/rack/render.rb', line 52

def get_content_type(env)
  fmt = env.params['format']
  fmt = fmt.last if fmt.is_a?(Array)

  type = if fmt.nil? || fmt =~ /^\s*$/
    ::Rack::RespondTo.selected_media_type
  else
    ::Rack::RespondTo::MediaType(fmt)
  end

  "#{type}; charset=utf-8"
end

- (Object) post_process(env, status, headers, body)



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/goliath/rack/render.rb', line 31

def post_process(env, status, headers, body)
  ::Rack::RespondTo.env = env

  # the respond_to block is what actually triggers the
  # setting of selected_media_type, so it's required

  respond_to do |format|
    format.json { body }
    format.html { body }
    format.xml { body }
    format.rss { body }
    format.js { body }
  end

  extra = { 'Content-Type' => get_content_type(env),
            'Server' => 'PostRank Goliath API Server',
            'Vary' => [headers.delete('Vary'), 'Accept'].compact.join(',') }

  [status, extra.merge(headers), body]
end