Default Value support
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 71
- Forks
- 27
- Avg merge
- 3h 3m
- Merged PRs (30d)
- 2
Description
Hi,
Thanks a lot for this gem!
I wrote a little hacky class that adds support for default values. So you can do:
parser.on('-m', '--tracing-mode MODE', 'Define the category of events traced', default: 'default')
I have no idea if you can find it interesting, but I use it quite often in my project, so I share it with you. Putting the default values into the into for me to duplicate the key (one into the the on and one into the into. I lead from some silly mistake due to a typo).
If you are interested, maybe I can try to do a cleaner PR. If you are not, please feel free to close this issue.
Thanks a lot!
require 'optparse'
class OptionParserWithDefaultAndValidation < OptionParser
def initialize
# Dictionary to save the default values passed by `on`
@defaults = {}
super
end
def parse!(argv = default_argv, into: nil)
# Merge the default value with the `into` dict
into.merge!(@defaults) unless into.nil?
# This will populate the `into` dict (overwriting our default if needed)
super
end
def define(*opts, &block)
switch = super
@defaults[switch.switch_name] = @tmp_default unless @tmp_default.nil?
switch
end
def on(*opts, default, &block)
# Save the default, which will be used in `refine.`
@tmp_default = default
# Default can contain Array (or Set).
# We cannot use the [a].flatten trick.
# So we use the respond_to one
# irb(main):028:0> default = Set[-1,2]
# => #<Set: {-1, 2}>
# irb(main):029:0> [default].flatten.join(',')
# => "#<Set: {-1, 2}>"
# irb(main):030:0> default.respond_to?(:flatten)? default.flatten.join(',') : default
# => "-1,2"
opts << "Default: #{default.respond_to?(:flatten) ? default.flatten.join(',') : default}" unless default.nil?
super(*opts, &block)
end
end
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the OptionParser#on, #define, and #parse! entry points shown in the proposed subclass, and review how the existing into argument is populated. Confirm the expected behavior for default values with and without into, then locate the existing OptionParser tests and use them to define completion criteria.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- cli
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100