Sha256: a942fea52c94e99cd2ad77f8b231507acb6a794ee8c53d0d5027f6c791b6419c

Contents?: true

Size: 1.11 KB

Versions: 3

Compression:

Stored size: 1.11 KB

Contents

# frozen_string_literal: true

module Basic101

  class ArgumentChecker

    def initialize(args, required_types, optional_types)
      @args = args
      @required_types = required_types
      @optional_types = optional_types
    end

    def check
      check_count
      check_types
    end

    private

    def check_count
      unless count_range.include?(@args.size)
        message = "Wrong number of arguments "\
        "(#{@args.size} instead of #{expected_count})"
        raise InvalidArgumentError, message
      end
    end

    def check_types
      @args.zip(types[0..@args.size]).each do |arg, type|
        unless arg.is_a?(type)
          raise InvalidArgumentError,
          "Expected #{type.type_name} but got #{arg.type_name}"
        end
      end
    end

    def expected_count
      if min_count == max_count
        min_count
      else
        count_range
      end
    end

    def count_range
      min_count..max_count
    end

    def min_count
      @required_types.size
    end

    def max_count
      types.size
    end

    def types
      @required_types + @optional_types
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
basic101-1.0.2 lib/basic101/argument_checker.rb
basic101-1.0.1 lib/basic101/argument_checker.rb
basic101-1.0.0 lib/basic101/argument_checker.rb