ruby / ruby/optparse

Default Value support

未关闭
#67 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Ruby
星标
71
派生
27
平均合并
3 小时 3 分钟
30 天内合并 PR
2

描述

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

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从提议的子类中显示的 OptionParser#on、#define 和 #parse! 入口点开始,检查现有的 into 参数是如何填充的。确认有无 into 时默认值的预期行为,然后找到现有的 OptionParser 测试,并使用它们定义完成标准。

由索引模型根据 Issue 内容生成。

评估

技术栈
ruby
领域
cli
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
需要澄清
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。