Class: Rack::AcceptHeaderUpdater

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

Overview

A Rack middleware for automatically removing file extensions from URIs, and update the Accept HTTP Header accordingly.

e.g.:

GET /some/resource.json HTTP/1.1
Accept: */*

->

GET /some/resource HTTP/1.1
Accept: application/json, */*

You can add custom types with this kind of function (taken from sinatra):

def mime(ext, type)
  ext = ".#{ext}" unless ext.to_s[0] == ?.
  Rack::Mime::MIME_TYPES[ext.to_s] = type
end

then:

mime :my_custom_extension_v1, 'application/vnd.com.example.MyCustomExtension+json;level=1'

results in the following behaviour:

GET /some/resource.my_custom_extension_v1 HTTP/1.1
Accept: */*

->

GET /some/resource HTTP/1.1
Accept: application/vnd.com.example.MyCustomExtension+json;level=1, */*

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of AcceptHeaderUpdater.



28
29
30
# File 'lib/rack/accept_header_updater.rb', line 28

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

Instance Method Details

#call(env) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/rack/accept_header_updater.rb', line 32

def call(env)
  req = Rack::Request.new(env)
  unless (ext = ::File.extname(req.path_info)).empty?
    if (mime_type = Rack::Mime::MIME_TYPES[ext.downcase])
      env['HTTP_ACCEPT'] = [mime_type, env['HTTP_ACCEPT']].join(",")
    end
    req.path_info.gsub!(/#{ext}$/, '')
  end
  @app.call(env)
end