Sha256: 68c9e24cc6d835c5364363557496cce77ce7f609a16e54dd1e5a84d3211abe00

Contents?: true

Size: 843 Bytes

Versions: 8

Compression:

Stored size: 843 Bytes

Contents

require 'optparse'

class Cl
  class Parser < OptionParser
    attr_reader :opts

    def initialize(opts, args)
      @opts = {}

      super do
        opts.each do |opt|
          on(*opt.strs) do |value|
            set(opt, value)
          end

          opt.aliases.each do |name|
            on(aliased(opt, name)) do |value|
              @opts[name] = set(opt, value)
            end
          end
        end
      end

      parse!(args)
    end

    def aliased(opt, name)
      str = opt.strs.detect { |str| str.start_with?('--') } || raise
      str.sub(opt.name.to_s, name.to_s)
    end

    # should consider negative arities (e.g. |one, *two|)
    def set(opt, value)
      args = [opts, opt.type, opt.name, value]
      args = args[-opt.block.arity, opt.block.arity]
      instance_exec(*args, &opt.block)
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
cl-0.1.7 lib/cl/parser.rb
cl-0.1.6 lib/cl/parser.rb
cl-0.1.5 lib/cl/parser.rb
cl-0.1.4 lib/cl/parser.rb
cl-0.1.3 lib/cl/parser.rb
cl-0.1.2 lib/cl/parser.rb
cl-0.1.1 lib/cl/parser.rb
cl-0.1.0 lib/cl/parser.rb