Sha256: db0194c1597bcea08b8ff32730cacfb1ac2b142dc06b9addaad6a11f673c4021

Contents?: true

Size: 1.92 KB

Versions: 2

Compression:

Stored size: 1.92 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, explicitly_no_params, param_defns)
      @raw_arguments = raw_arguments
      @explicitly_no_params = explicitly_no_params
      @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 !@explicitly_no_params && @param_defns.empty?
        # No parameters defined; ignore
        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

2 entries across 2 versions & 1 rubygems

Version Path
cri-2.14.0 lib/cri/argument_list.rb
cri-2.13.0 lib/cri/argument_list.rb