Sha256: 0e14d2da12e5ff8ffeca55d849c7db3c89c1d5227d94799b7a0c448a95050265

Contents?: true

Size: 1.27 KB

Versions: 2

Compression:

Stored size: 1.27 KB

Contents

module Rack
  #
  # 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, */*
  # 
  class AcceptHeaderUpdater

    def initialize(app, options = {})
      @app = app
    end
  
    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    
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rack-accept-header-updater-1.0.1 lib/rack/accept_header_updater.rb
rack-accept-header-updater-1.0.0 lib/rack/accept_header_updater.rb