diff options
author | Lee Jarvis <ljjarvis@gmail.com> | 2013-01-08 11:36:27 +0000 |
---|---|---|
committer | Lee Jarvis <ljjarvis@gmail.com> | 2013-01-08 11:36:27 +0000 |
commit | 0a4ccdb268c3cddb80a427a509a0243c54f3dd16 (patch) | |
tree | beda573c769f131725ff3aabfb71618239ecb55c | |
parent | d5a43ffa81fb8a0e0a7c582f737fad00f88ac8e2 (diff) | |
download | slop-0a4ccdb268c3cddb80a427a509a0243c54f3dd16.tar.gz |
added basic command implementation merging into Slop
ref #95
-rw-r--r-- | lib/slop.rb | 49 |
1 files changed, 47 insertions, 2 deletions
diff --git a/lib/slop.rb b/lib/slop.rb index 337dd8f..853df56 100644 --- a/lib/slop.rb +++ b/lib/slop.rb @@ -124,6 +124,7 @@ class Slop def initialize(config = {}, &block) @config = DEFAULT_OPTIONS.merge(config) @options = [] + @commands = {} @trash = [] @triggered_options = [] @unknown_options = [] @@ -152,8 +153,6 @@ class Slop # Set the banner. # # banner - The String to set the banner. - # - # Returns nothing. def banner=(banner) config[:banner] = banner end @@ -168,6 +167,33 @@ class Slop config[:banner] end + # Set the description (used for commands). + # + # desc - The String to set the description. + def description=(desc) + config[:description] = desc + end + + # Get or set the description (used for commands). + # + # desc - The String to set the description. + # + # Returns the description String. + def description(desc = nil) + config[:description] = desc if desc + config[:description] + end + + # Add a new command. + # + # command - The Symbol or String used to identify this command. + # options - A Hash of configuration options (see Slop::new) + # + # Returns a new instance of Slop mapped to this command. + def command(command, options = {}, &block) + @commands[command.to_s] = Slop.new(options, &block) + end + # Parse a list of items, executing and gathering options along the way. # # items - The Array of items to extract options from (default: ARGV). @@ -193,6 +219,10 @@ class Slop return items end + if cmd = @commands[items[0]] + return cmd.parse! items[1..-1] + end + items.each_with_index do |item, index| @trash << index && break if item == '--' autocreate(items, index) if config[:autocreate] @@ -371,6 +401,13 @@ class Slop (str = @separators[i + 1]) ? [o, str].join("\n") : o }.join("\n") + if @commands.any? + optstr << "\n" if !optstr.empty? + optstr << "\nAvailable commands:\n\n" + optstr << commands_to_help + optstr << "\n\nSee `<command> --help` for more information on a specific command." + end + banner = config[:banner] if banner "#{banner}\n#{@separators[0] ? "#{@separators[0]}\n" : ''}#{optstr}" @@ -602,4 +639,12 @@ class Slop object.to_s.sub(/\A--?/, '') end + def commands_to_help + padding = 0 + @commands.each { |c, _| padding = c.size if c.size > padding } + @commands.map do |cmd, opts| + " #{cmd}#{' ' * (padding - cmd.size)} #{opts.description}" + end.join("\n") + end + end |