diff --git a/bin/example.rb b/bin/example.rb index 03787b4..4291c54 100755 --- a/bin/example.rb +++ b/bin/example.rb @@ -4,8 +4,9 @@ require 'pathname' $:.unshift Pathname.new(__FILE__).dirname.dirname.join('lib').to_s require 'dencli' -cli = DenCli.new 'example', "This is an example for generate a DenCli-API" -cli.cmd( :args, "Expects and prints given arguments", &lambda {|a, b, c:, d:, e:| +cli = DenCli.new :example, "This is an example for generate a DenCli-API" +cli.cmd( :args, "Expects and prints given arguments", + &lambda {|a, b, c:, d:, e:| p a: a, b: b, c: c, d: d, e: e }). opt( :c, '-c=ForC', "Option c"). diff --git a/lib/dencli.rb b/lib/dencli.rb index 7681856..c9c8264 100755 --- a/lib/dencli.rb +++ b/lib/dencli.rb @@ -1,6 +1,13 @@ require 'optparse' + class DenCli + def self.assert_type klass, method, argument_name, object, *types + unless types.any? {|type| object.is_a? type } + raise ArgumentError, "#{klass.name}.#{method} expects #{types.map( &:to_s).join '|' } for #{argument_name}, not: #{object.inspect}" + end + end + class UsageError < ::RuntimeError end class UnknownCommand < UsageError diff --git a/lib/dencli/cmd.rb b/lib/dencli/cmd.rb index 12cad0a..1e4bfe1 100644 --- a/lib/dencli/cmd.rb +++ b/lib/dencli/cmd.rb @@ -80,8 +80,8 @@ class DenCli::CMD end end - def commands *args, &exe - yield self + def commands *args + yield name, self end def goto *args diff --git a/lib/dencli/sub.rb b/lib/dencli/sub.rb index c52ddc7..15207d5 100644 --- a/lib/dencli/sub.rb +++ b/lib/dencli/sub.rb @@ -4,6 +4,9 @@ class DenCli::Sub attr_reader :parent, :name, :description, :subs, :aliases def initialize parent, name, description + #DenCli::assert_type self, __method__, :name, name, Symbol + #DenCli::assert_type self, __method__, :parent, parent, DenCli, DenCli::Sub + #DenCli::assert_type self, __method__, :description, description, String @parent, @name, @description, @subs, @aliases = parent, name, "-> #{description}", {}, {} end @@ -33,7 +36,7 @@ class DenCli::Sub end def commands &exe - yield self + yield name, self @subs.each {|k, c| c.commands &exe } end @@ -44,8 +47,8 @@ class DenCli::Sub end def self._help_commands output, subs - m = subs.map {|c| x = c.usage.length; 25 < x ? 0 : x }.max - subs.each do |c| + m = subs.map {|_name,c| x = c.usage.length; 25 < x ? 0 : x }.max + subs.each do |_name, c| if 25 < c.usage.length output << "% -#{m}s\n#{' ' * m} " % [c.usage] else @@ -96,6 +99,10 @@ class DenCli::Sub end def _add name, min, obj, aliases + #DenCli::assert_type self, __method__, :name, name, Symbol, NilClass + #DenCli::assert_type self, __method__, :min, min, Integer, NilClass + #DenCli::assert_type self, __method__, :obj, obj, DenCli::Sub, DenCli::CMD + #DenCli::assert_type self, __method__, :aliases, aliases, Array, NilClass name = name.to_s unless name.nil? @subs[name] = obj DenCli.gen_aliases( name, min) {|a| @aliases[a] = obj }