Class: Grape::Middleware::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/middleware/base.rb

Constant Summary collapse

CONTENT_TYPES =

Content types are listed in order of preference.

ActiveSupport::OrderedHash[
  :xml,  'application/xml',
  :serializable_hash, 'application/json',
  :json, 'application/json',
  :atom, 'application/atom+xml',
  :rss,  'application/rss+xml',
  :txt,  'text/plain',
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Base

Returns a new instance of Base.

Parameters:

  • app (Rack Application)

    The standard argument for a Rack middleware.

  • options (Hash) (defaults to: {})

    A hash of options, simply stored for use by subclasses.



22
23
24
25
# File 'lib/grape/middleware/base.rb', line 22

def initialize(app, options = {})
  @app = app
  @options = default_options.merge(options)
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



18
19
20
# File 'lib/grape/middleware/base.rb', line 18

def app
  @app
end

#envObject (readonly)

Returns the value of attribute env.



18
19
20
# File 'lib/grape/middleware/base.rb', line 18

def env
  @env
end

#optionsObject (readonly)

Returns the value of attribute options.



18
19
20
# File 'lib/grape/middleware/base.rb', line 18

def options
  @options
end

Instance Method Details

#afterResponse?

This method is abstract.

Called after the application is called in the middleware lifecycle.

Returns:

  • (Response, nil)

    a Rack SPEC response or nil to call the application afterwards.



46
# File 'lib/grape/middleware/base.rb', line 46

def after; end

#beforeObject

This method is abstract.

Called before the application is called in the middleware lifecycle.



42
# File 'lib/grape/middleware/base.rb', line 42

def before; end

#call(env) ⇒ Object



29
30
31
# File 'lib/grape/middleware/base.rb', line 29

def call(env)
  dup.call!(env)
end

#call!(env) ⇒ Object



33
34
35
36
37
38
# File 'lib/grape/middleware/base.rb', line 33

def call!(env)
  @env = env
  before
  @app_response = @app.call(@env)
  after || @app_response
end

#content_typeObject



60
61
62
# File 'lib/grape/middleware/base.rb', line 60

def content_type
  content_types[env['api.format'] || options[:format]] || 'text/html'
end

#content_typesObject



56
57
58
# File 'lib/grape/middleware/base.rb', line 56

def content_types
  options[:content_types] || CONTENT_TYPES
end

#default_optionsObject



27
# File 'lib/grape/middleware/base.rb', line 27

def default_options; {} end

#mime_typesObject



64
65
66
# File 'lib/grape/middleware/base.rb', line 64

def mime_types
  content_types.invert
end

#requestObject



48
49
50
# File 'lib/grape/middleware/base.rb', line 48

def request
  Rack::Request.new(self.env)
end

#responseObject



52
53
54
# File 'lib/grape/middleware/base.rb', line 52

def response
  Rack::Response.new(@app_response)
end