Sha256: 02e7da9834a4d2e828d94c6d2dd16948d4522db6c0abe259256efd65ffb6ca7e

Contents?: true

Size: 1.66 KB

Versions: 43

Compression:

Stored size: 1.66 KB

Contents

module HTTP
  # MIME type encode/decode adapters
  module MimeType
    class << self
      # Associate MIME type with adapter
      #
      # @example
      #
      #   module JsonAdapter
      #     class << self
      #       def encode(obj)
      #         # encode logic here
      #       end
      #
      #       def decode(str)
      #         # decode logic here
      #       end
      #     end
      #   end
      #
      #   HTTP::MimeType.register_adapter 'application/json', MyJsonAdapter
      #
      # @param [#to_s] type
      # @param [#encode, #decode] adapter
      # @return [void]
      def register_adapter(type, adapter)
        adapters[type.to_s] = adapter
      end

      # Returns adapter associated with MIME type
      #
      # @param [#to_s] type
      # @raise [Error] if no adapter found
      # @return [Class]
      def [](type)
        adapters[normalize type] || fail(Error, "Unknown MIME type: #{type}")
      end

      # Register a shortcut for MIME type
      #
      # @example
      #
      #   HTTP::MimeType.register_alias 'application/json', :json
      #
      # @param [#to_s] type
      # @param [#to_sym] shortcut
      # @return [void]
      def register_alias(type, shortcut)
        aliases[shortcut.to_sym] = type.to_s
      end

      # Resolves type by shortcut if possible
      #
      # @param [#to_s] type
      # @return [String]
      def normalize(type)
        aliases.fetch type, type.to_s
      end

      private

      # :nodoc:
      def adapters
        @adapters ||= {}
      end

      # :nodoc:
      def aliases
        @aliases ||= {}
      end
    end
  end
end

# built-in mime types
require "http/mime_type/json"

Version data entries

43 entries across 43 versions & 1 rubygems

Version Path
http-2.0.0.pre lib/http/mime_type.rb
http-1.0.4 lib/http/mime_type.rb
http-0.9.9 lib/http/mime_type.rb
http-1.0.3 lib/http/mime_type.rb
http-1.0.2 lib/http/mime_type.rb
http-1.0.1 lib/http/mime_type.rb
http-1.0.0 lib/http/mime_type.rb
http-1.0.0.pre6 lib/http/mime_type.rb
http-1.0.0.pre5 lib/http/mime_type.rb
http-1.0.0.pre4 lib/http/mime_type.rb
http-1.0.0.pre3 lib/http/mime_type.rb
http-1.0.0.pre2 lib/http/mime_type.rb
http-1.0.0.pre1 lib/http/mime_type.rb
http-0.9.8 lib/http/mime_type.rb
http-0.9.7 lib/http/mime_type.rb
http-0.9.6 lib/http/mime_type.rb
http-0.9.5 lib/http/mime_type.rb
http-0.9.4 lib/http/mime_type.rb
http-0.9.3 lib/http/mime_type.rb
http-0.8.14 lib/http/mime_type.rb