Sha256: e940e93654c69c85477a541a184c26967ee32f34f45f9a37186e0f48baf60bd4

Contents?: true

Size: 1.44 KB

Versions: 27

Compression:

Stored size: 1.44 KB

Contents

require 'cl/arg'

class Cl
  class Args
    include Enumerable

    def define(const, name, *args)
      opts = args.last.is_a?(Hash) ? args.pop.dup : {}
      opts[:description] = args.shift if args.any?

      arg = Arg.new(name, opts)
      arg.define(const)
      self.args << arg
    end

    def apply(cmd, args, opts)
      return args if self.args.empty? || opts[:help]
      args = grouped(args)
      validate(args)
      args.map { |(arg, value)| arg.set(cmd, value) }.flatten(1)
    end

    def each(&block)
      args.each(&block)
    end

    def index(*args, &block)
      self.args.index(*args, &block)
    end

    def args
      @args ||= []
    end

    private

      def validate(args)
        raise ArgumentError.new(:missing_args, args.size, required) if args.size < required
        raise ArgumentError.new(:too_many_args, args.size, allowed) if args.size > allowed && !splat?
      end

      def allowed
        args.size
      end

      def splat?
        any?(&:splat?)
      end

      def required
        select(&:required?).size
      end

      def grouped(values)
        values.inject([0, {}]) do |(ix, group), value|
          arg = args[ix]
          if arg && arg.splat?
            group[arg] ||= []
            group[arg] << value
            ix += 1 if args.size + group[arg].size > values.size
          else
            group[arg] = value
            ix += 1
          end
          [ix, group]
        end.last
      end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
cl-1.0.0 lib/cl/args.rb
cl-0.1.28 lib/cl/args.rb
cl-0.1.27 lib/cl/args.rb
cl-0.1.26 lib/cl/args.rb
cl-0.1.25 lib/cl/args.rb
cl-0.1.24 lib/cl/args.rb
cl-0.1.23 lib/cl/args.rb
cl-0.1.22 lib/cl/args.rb
cl-0.1.21 lib/cl/args.rb
cl-0.1.20 lib/cl/args.rb
cl-0.1.19 lib/cl/args.rb
cl-0.1.18 lib/cl/args.rb
cl-0.1.17 lib/cl/args.rb
cl-0.1.16 lib/cl/args.rb
cl-0.1.15 lib/cl/args.rb
cl-0.1.14 lib/cl/args.rb
cl-0.1.13 lib/cl/args.rb
cl-0.1.12 lib/cl/args.rb
cl-0.1.11 lib/cl/args.rb
cl-0.1.10 lib/cl/args.rb