class Ditty::Middleware::AcceptExtension

Allow requests to be responded to in JSON if the URL has .json at the end. The regex and the content_type can be customized to allow for other formats. Some inspiration from gist.github.com/tstachl/6264249

Attributes

content_type[R]
env[R]
regex[R]

Public Class Methods

new(app, regex = %r{\A(.*)\.json(/?)\Z}, content_type = 'application/json') click to toggle source
# File lib/ditty/middleware/accept_extension.rb, line 11
def initialize(app, regex = %r{\A(.*)\.json(/?)\Z}, content_type = 'application/json')
  # @mutex = Mutex.new
  @app = app
  @regex = regex
  @content_type = content_type
end

Public Instance Methods

call(env) click to toggle source
# File lib/ditty/middleware/accept_extension.rb, line 18
def call(env)
  @env = env

  request = Rack::Request.new(env)
  if request.path&.match?(regex)
    request.path_info = request.path_info.gsub(regex, '\1\2')
    env = request.env
    env['ACCEPT'] = content_type
    env['CONTENT_TYPE'] = content_type
  end

  @app.call env
end