Sha256: 97cf5f9601ebd87bc1c33dfaf0124ed0f865d5eaea3c4cea091e8bc00f165a13

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

module Cri
  # A list of arguments, which can be indexed using either a number or a symbol.
  class ArgumentList
    # Error that will be raised when an incorrect number of arguments is given.
    class ArgumentCountMismatchError < Cri::Error
      def initialize(expected_count, actual_count)
        @expected_count = expected_count
        @actual_count = actual_count
      end

      def message
        "incorrect number of arguments given: expected #{@expected_count}, but got #{@actual_count}"
      end
    end

    include Enumerable

    def initialize(raw_arguments, param_defns)
      @raw_arguments = raw_arguments
      @param_defns = param_defns

      load
    end

    def [](key)
      case key
      when Symbol
        @arguments_hash[key]
      when Integer
        @arguments_array[key]
      else
        raise ArgumentError, "argument lists can be indexed using a Symbol or an Integer, but not a #{key.class}"
      end
    end

    def each
      @arguments_array.each { |e| yield(e) }
      self
    end

    def method_missing(sym, *args, &block)
      if @arguments_array.respond_to?(sym)
        @arguments_array.send(sym, *args, &block)
      else
        super
      end
    end

    def respond_to_missing?(sym, include_private = false)
      @arguments_array.respond_to?(sym) || super
    end

    def load
      @arguments_array = @raw_arguments.reject { |a| a == '--' }.freeze
      @arguments_hash = {}

      if @param_defns.empty?
        # For now, don’t check arguments when no parameter definitions are given.
        return
      end

      if @arguments_array.size != @param_defns.size
        raise ArgumentCountMismatchError.new(@param_defns.size, @arguments_array.size)
      end

      @arguments_array.zip(@param_defns).each do |(arg, param_defn)|
        @arguments_hash[param_defn.name.to_sym] = arg
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cri-2.12.0 lib/cri/argument_list.rb