Skip to content

Commit

Permalink
Add support for default settings, which are applied on every argument
Browse files Browse the repository at this point in the history
  • Loading branch information
florianpilz committed Dec 29, 2013
1 parent 97867c1 commit 0477e44
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ So µ-optparse is for you if you are looking for
What is µ-optparse?
-------------------

µ-optparse is a small wrapper around [optparse](http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html), weighing **less than 75 lines of code**.
µ-optparse is a small wrapper around [optparse](http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html), weighing **less than 80 lines of code**.
optparse (or OptionParser) on the other hand is a command line parser, which ships with ruby.
After you defined available options, it automatically creates a help page and is able to parse ARGV accordingly.
However, optparse requires you to repeat yourself quite often, which leads to many lines of code, just to configure the available options.
Expand Down
4 changes: 3 additions & 1 deletion lib/micro-optparse/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

class Parser
attr_accessor :banner, :version
def initialize
def initialize(default_settings = {})
@options = []
@used_short = []
@default_values = {}
@default_settings = default_settings
yield self if block_given?
end

def option(name, desc, settings = {})
settings = @default_settings.clone.merge(settings)
@options << {:name => name, :description => desc, :settings => settings}
end

Expand Down
23 changes: 23 additions & 0 deletions spec/parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,29 @@
result[:second_listarg].should == ['blah', 'blah', 'blah']
end
end

describe "default settings" do
it "should set default settings on all options" do
parser = Parser.new(:optional => true) do |p|
p.option :foo, "foo argument"
p.option :bar, "bar argument"
end

result = parser.process!([])
result.length.should == 0 # all optional
end

it "should allow to overwrite default settings" do
parser = Parser.new(:default => "Bar") do |p|
p.option :foo, "foo argument", :default => "Foo"
p.option :bar, "bar argument"
end

result = parser.process!([])
result[:foo].should == "Foo"
result[:bar].should == "Bar"
end
end

describe "help message" do
it "should show help message when called with --help or -h" do
Expand Down

0 comments on commit 0477e44

Please sign in to comment.