Sha256: a7b913aa847971bc576d7f021a5d8864a1be3881910a012aa9149a435e754c93

Contents?: true

Size: 906 Bytes

Versions: 4

Compression:

Stored size: 906 Bytes

Contents

module Ditty
  module Middleware
    # 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 https://gist.github.com/tstachl/6264249
    class AcceptExtension
      attr_reader :env, :regex, :content_type

      def initialize(app, regex = /\A(.*)\.json(\/?)\Z/, content_type = 'application/json')
        # @mutex = Mutex.new
        @app = app
        @regex = regex
        @content_type = content_type
      end

      def call(env)
        @env = env

        request = Rack::Request.new(env)
        if request.path =~ 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
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ditty-0.7.2 lib/ditty/middleware/accept_extension.rb
ditty-0.7.1 lib/ditty/middleware/accept_extension.rb
ditty-0.7.0 lib/ditty/middleware/accept_extension.rb
ditty-0.7.0.pre.rc1 lib/ditty/middleware/accept_extension.rb