Sha256: 2d8e664e817541c2644cd2f99f4ac9e00071d9a8683f2be9ed7f55dd49b8305f

Contents?: true

Size: 1.12 KB

Versions: 7

Compression:

Stored size: 1.12 KB

Contents

module RspecApiDocs
  module After
    class TypeChecker
      UnknownType = Class.new(BaseError)
      TypeError = Class.new(BaseError)

      attr_reader :type, :value

      def self.call(*args)
        new(*args).check
      end

      def initialize(type:, value:)
        @type = type
        @value = value
      end

      def check
        case type
        when /integer/i
          is_integer?(value) or raise_type_error
        when /float/i
          is_float?(value) or raise_type_error
        when /boolean/i
          is_bool?(value) or raise_type_error
        when /string/i
          # NO OP
        else
          raise UnknownType, "unknown type #{type.inspect}"
        end
      end

      private

      def is_integer?(str)
        Integer(str) && true
      rescue ArgumentError
        false
      end

      def is_float?(str)
        Float(str) && true
      rescue ArgumentError
        false
      end

      def is_bool?(str)
        %w[true false].include?(str)
      end

      def raise_type_error
        raise TypeError, "wrong type #{value.inspect}, expected #{type.inspect}"
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rspec-api-docs-1.1.0 lib/rspec_api_docs/after/type_checker.rb
rspec-api-docs-1.0.0 lib/rspec_api_docs/after/type_checker.rb
rspec-api-docs-0.14.0 lib/rspec_api_docs/after/type_checker.rb
rspec-api-docs-0.13.0 lib/rspec_api_docs/after/type_checker.rb
rspec-api-docs-0.12.0 lib/rspec_api_docs/after/type_checker.rb
rspec-api-docs-0.11.0 lib/rspec_api_docs/after/type_checker.rb
rspec-api-docs-0.10.0 lib/rspec_api_docs/after/type_checker.rb