Sha256: 67f2ac4d41686000f9687b5afd68fb39acd41340da9ff9bb23d67f4cbf2728f6

Contents?: true

Size: 1.35 KB

Versions: 2

Compression:

Stored size: 1.35 KB

Contents

require 'grape/middleware/base'
require 'active_support/json'

module Grape
  module Middleware
    class Formatter < Base
      CONTENT_TYPES = {
        :xml => 'application/xml',
        :json => 'application/json',
        :atom => 'application/atom+xml',
        :rss => 'application/rss+xml'
      }
      
      def default_options
        { 
          :default_format => :json,
          :content_types => {}
        }
      end
      
      def content_types
        CONTENT_TYPES.merge(options[:content_types])
      end
      
      def before
        fmt = format_from_extension || format_from_header || options[:default_format]
        
        if content_types.key?(fmt)
          env['api.format'] = fmt          
        else
          throw :error, :status => 406, :message => 'The requested format is not supported.'
        end
      end
      
      def format_from_extension
        parts = request.path.split('.')
        hit = parts.last.to_sym
        
        if parts.size <= 1
          nil
        else
          hit
        end
      end
      
      def format_from_header
        # TODO: Implement Accept header parsing.
      end
      
      def after
        status, headers, bodies = *@app_response
        bodies.map! do |body|
          ActiveSupport::JSON.encode(body)
        end
        [status, headers, bodies]
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
grape-0.0.0.alpha.2 lib/grape/middleware/formatter.rb
grape-0.0.0.alpha.1 lib/grape/middleware/formatter.rb