Sha256: e242e848e13e8cad01c1915bd6d0cae3122358347c72d74d55160eaeea234f3e

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

require 'optparse'
require 'zan_tools/spring_generator'
require 'zan_tools/version'

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.separator "common options"
        # 其他参数
        opts.on("-o", "--output FILE", "输出到指定文件") do |value|
          options[:output] = value
        end
        opts.on("-v", "--version", "zan_tools版本") do |value|
          options[:version] = ZanTools::VERSION
        end
      end
      parser.parse!

      case ARGV[0]
      when 'g', 'generate'
        generate
      else
        puts options[:version] if options[:version]
      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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
zan_tools-0.1.3 lib/zan_tools/command.rb