Sha256: 65042b9f032376088d0cdf778a94addec4e453e4937a7eb69a74b8306294535e

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

require "hanami/utils/class"
require "hanami/utils/string"
require_relative "errors"

module Hanami
  module Middleware
    class BodyParser
      # @api private
      # @since 1.3.0
      module ClassInterface
        # @api private
        # @since 1.3.0
        def for(parser) # rubocop:disable Metrics/MethodLength
          parser =
            case parser
            when String, Symbol
              require_parser(parser)
            when Class
              parser.new
            else
              parser
            end

          ensure_parser parser

          parser
        end

        private

        # @api private
        # @since 1.3.0
        PARSER_METHODS = %i[mime_types parse].freeze

        # @api private
        # @since 1.3.0
        def ensure_parser(parser)
          raise InvalidParserError.new(parser) unless PARSER_METHODS.all? { |method| parser.respond_to?(method) }
        end

        # @api private
        # @since 1.3.0
        def require_parser(parser)
          require "hanami/middleware/body_parser/#{parser}_parser"

          parser = Utils::String.classify(parser)
          Utils::Class.load!("Hanami::Middleware::BodyParser::#{parser}Parser").new
        rescue LoadError, NameError
          raise UnknownParserError.new(parser)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hanami-router-2.0.0.alpha1 lib/hanami/middleware/body_parser/class_interface.rb