Sha256: 643ff63d4156180da75d114ecdf1cc69b73ef2f8d1dd530683a5fe1868b44fc3

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

require 'optparse'

module Ds
  class Command
    module Options

      def self.parse!(argv)
        options = {}

        command_parser = create_command_parser

        # 引数の解析を行う
        begin
          command_parser.order!(argv)

          options[:command] = argv.shift

          if %w(create update delete list).include?(options[:command])
            raise ArgumentError, "#{options[:command]} id not found." if argv.empty?
            options[:id] = Integer(argv.first)
          end
        rescue OptionParser::MissingArgument, OptionParser::InvalidOption, ArgumentError => e
          abort e.message
        end

        options
      end

      def self.create_command_parser
        command_parser = OptionParser.new do |opt|
          sub_command_help = [
            { name: 'create -c content -t time',    summary: 'Create Do with time' },
            { name: 'update id -t time',            summary: 'Update Do\'s total time' },
            { name: 'delete id',                    summary: 'Delete Do' },
            { name: 'list',                         summary: 'Do List' }
          ]

          opt.banner = "Usage: #{opt.program_name} [-h|--help] [-v|--version] <command> [<args]"
          opt.separator ''
          opt.separator "#{opt.program_name} Available Commands:"
          sub_command_help.each do |command|
            opt.separator [opt.summary_indent, command[:name].ljust(40), command[:summary]].join(' ')
          end

          opt.on_head('-h', '--help', 'Show this message') do
            puts opt.help
            exit
          end

          opt.on_head('-v', '--version', 'Show program version') do
            opt.version = Ds::VERSION
            puts opt.ver
            exit
          end
        end
      end

      private_class_method :create_command_parser
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mdg-1.0.1 vendor/bundle/ruby/2.3.0/gems/ds-0.0.2/lib/ds/command/options.rb