Sha256: 266cfed867227a0bbd3e0e900630ade1a276afb986dd4909d8f83ebd733bba0e

Contents?: true

Size: 1.69 KB

Versions: 36

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

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] || raise(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

36 entries across 36 versions & 3 rubygems

Version Path
direct7-0.0.18 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/mime_type.rb
direct7-0.0.17 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/mime_type.rb
direct7-0.0.16 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/mime_type.rb
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/http-5.2.0/lib/http/mime_type.rb
direct7-0.0.13 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/mime_type.rb
direct7-0.0.12 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/mime_type.rb
http-5.2.0 lib/http/mime_type.rb
direct7-0.0.11 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/mime_type.rb
http-5.1.1 lib/http/mime_type.rb
http-5.1.0 lib/http/mime_type.rb
http-5.0.4 lib/http/mime_type.rb
http-5.0.3 lib/http/mime_type.rb
http-5.0.2 lib/http/mime_type.rb
http-5.0.1 lib/http/mime_type.rb
http-5.0.0 lib/http/mime_type.rb
http-4.4.1 lib/http/mime_type.rb
http-4.4.0 lib/http/mime_type.rb
http-5.0.0.pre3 lib/http/mime_type.rb
http-5.0.0.pre2 lib/http/mime_type.rb
http-4.3.0 lib/http/mime_type.rb