Really Cheap Command-Line Option Parsing in Ruby

前端 未结 20 1073
野的像风
野的像风 2020-11-30 16:57

EDIT: Please, please, please read the two requirements listed at the bottom of this post before replying. People keep posting their new gems and li

相关标签:
20条回答
  • 2020-11-30 17:25

    This is what I use for really, really cheap args:

    def main
      ARGV.each { |a| eval a }
    end
    
    main
    

    so if you run programname foo bar it calls foo and then bar. It's handy for throwaway scripts.

    0 讨论(0)
  • 2020-11-30 17:25

    Have you considered Thor by wycats? I think it's a lot cleaner than optparse. If you already have a script written, it might be some more work to format it or refactor it for thor, but it does make handling options very simple.

    Here's the example snippet from the README:

    class MyApp < Thor                                                # [1]
      map "-L" => :list                                               # [2]
    
      desc "install APP_NAME", "install one of the available apps"    # [3]
      method_options :force => :boolean, :alias => :optional          # [4]
      def install(name)
        user_alias = options[:alias]
        if options.force?
          # do something
        end
        # ... other code ...
      end
    
      desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
      def list(search = "")
        # list everything
      end
    end
    

    Thor automatically maps commands as such:

    app install myname --force
    

    That gets converted to:

    MyApp.new.install("myname")
    # with {'force' => true} as options hash
    
    1. Inherit from Thor to turn a class into an option mapper
    2. Map additional non-valid identifiers to specific methods. In this case, convert -L to :list
    3. Describe the method immediately below. The first parameter is the usage information, and the second parameter is the description.
    4. Provide any additional options. These will be marshaled from -- and - params. In this case, a --force and a -f option is added.
    0 讨论(0)
提交回复
热议问题