Class: ZanTools::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/zan_tools/command.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCommand

Returns a new instance of Command.



9
10
11
# File 'lib/zan_tools/command.rb', line 9

def initialize
  @options = {}
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/zan_tools/command.rb', line 7

def options
  @options
end

Instance Method Details

#generateObject



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/zan_tools/command.rb', line 54

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

#parse!Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/zan_tools/command.rb', line 13

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