require 'optparse' require 'zan_tools/spring_generator' module ZanTools class Command attr_reader :options def initialize @options = {} end def parse! parser = OptionParser.new do |opts| opts.banner = "Usage zan_tools COMMAND [options]" opts.separator "COMMAND" opts.separator " g/generate: 根据指定模板生成代码" opts.separator "generate options" # generate命令参数 opts.on("-n", "--name NAME", "表名或者类名") do |value| options[:name] = value end opts.on("-f", "--fields FIELDS", "字段列表,格式:字段1:类型2,字段2:类型2") do |value| options[:fields] = value.split(",").map{|f| f.split(":") }.select{|a| a.size==2 }.map{|k, v| [k, {'type'=>v}] } end opts.on("-t", "--template TEMPLATE", "模板文件") do |value| if File.exists?(value) options[:template] = File.read(value) else raise "template file not exists" end end # 其他参数 opts.on("-o", "--output FILE", "输出到指定文件") do |value| options[:output] = value end end parser.parse! case ARGV[0] when 'g', 'generate' generate end rescue StandardError => e puts [e.class, e.message].join(': ') end def generate raise "generate命令缺失参数" if %w{name fields template}.any?{|f| options[f.to_sym].nil? } ZanTools::SpringGenerator.init!(options[:name], options[:fields]) content = ZanTools::SpringGenerator.compile(options[:template]) if options[:output].nil? puts content else File.write(file, content) end end end end