Class: ApiVersions::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/api-versions/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



3
4
5
# File 'lib/api-versions/middleware.rb', line 3

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/api-versions/middleware.rb', line 7

def call(env)
  accept_string = env['HTTP_ACCEPT'] || ""
  accepts = accept_string.split(',')
  accepts.push("application/vnd.#{ApiVersions::VersionCheck.vendor_string}+json") unless accept_string.include?('application/vnd.')
  offset = 0
  accepts.dup.each_with_index do |accept, i|
    accept.strip!
    match = /\Aapplication\/vnd\.#{ApiVersions::VersionCheck.vendor_string}\s*\+\s*(?<format>\w+)\s*/.match(accept)
    if match
      accepts.insert i + offset, "application/#{match[:format]}"
      offset += 1
    end
  end

  env['HTTP_ACCEPT'] = accepts.join(',')
  @app.call(env)
end