# coding: utf-8 require 'optparse' module Recorder class Command module Options def self.parse!(argv) options = {} sub_command_parsers = create_sub_command_parsers(options) command_parser = create_command_parser begin command_parser.order!(argv) options[:command] = argv.shift sub_command_parsers[options[:command]].parse!(argv) if %(update delete).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_sub_command_parsers(options) sub_command_parsers = Hash.new do |k,v| raise ArgumentError, "'#{v} is not recorder sub command." end sub_command_parsers['create'] = OptionParser.new do |opt| opt.banner = 'Usage: create ' opt.on('-w VAL','--weight=VAL', 'data weight'){|v| options[:weight] = v} opt.on('-b VAL','--bodyfat=VAL','data bodyfat'){|v| options[:bodyfat] = v} opt.on_tail('-h','--help', 'Show this message') {|v| help_sub_command(opt) } end sub_command_parsers['update'] = OptionParser.new do |opt| opt.banner = 'Usage: update id ' opt.on('-d VAL','--date=VAL','update date'){|v| options[:date] = v} opt.on_tail('-h','--help', 'Show this message') {|v| help_sub_command(opt) } end sub_command_parsers['list'] = OptionParser.new do |opt| opt.banner = 'Usage: list id ' opt.on_tail('-h','--help', 'Show this message') {|v| help_sub_command(opt) } end sub_command_parsers['delete'] = OptionParser.new do |opt| opt.banner = 'Usage: delete id' opt.on_tail('-h','--help', 'Show this message') {|v| help_sub_command(opt) } end return sub_command_parsers end def self.help_sub_command(parser) puts parser.help exit end def self.create_command_parser OptionParser.new do |opt| sub_command_help = [ {name: 'create -w weight -b bodyfat', summary: 'Create Data'}, {name: 'update id -w weiht -b bodyfat -d date', summary: 'Update Data'}, {name: 'delete id', summary: 'Delete Data'} ] opt.banner = "Usage: #{opt.program_name} [-h|--help] [-v|--version] []" 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|v| puts opt.help exit end opt.on_head('-v','--version','show program version') do |v| opt.version = Recorder::VERSION puts opt.ver exit end end end end end end