Class: Tengine::Support::Config::Definition::OptparseVisitor

Inherits:
Object
  • Object
show all
Defined in:
lib/tengine/support/config/definition/optparse_visitor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(suite) ⇒ OptparseVisitor

Returns a new instance of OptparseVisitor.



9
10
11
12
# File 'lib/tengine/support/config/definition/optparse_visitor.rb', line 9

def initialize(suite)
  @option_parser = OptionParser.new
  @suite = suite
end

Instance Attribute Details

#option_parserObject (readonly) Also known as: o

Returns the value of attribute option_parser.



8
9
10
# File 'lib/tengine/support/config/definition/optparse_visitor.rb', line 8

def option_parser
  @option_parser
end

Instance Method Details

#visit(d) ⇒ Object



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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/tengine/support/config/definition/optparse_visitor.rb', line 16

def visit(d)
  return if d.respond_to?(:hidden?) && d.hidden?
  case d
  when Tengine::Support::Config::Definition::Suite then
    option_parser.banner = d.banner
    d.children.each{|child| child.accept_visitor(self)}
  when Tengine::Support::Config::Definition::Group then
    if d.children.any?{|c| c.is_a?(Tengine::Support::Config::Definition::Field)}
      o.separator ""
      o.separator "#{d.__name__}:"
    end
    d.children.each{|child| child.accept_visitor(self)}
  when Tengine::Support::Config::Definition then
    o.separator ""
    o.separator "#{d.__name__}:"
    d.children.each{|child| child.accept_visitor(self)}
  when Tengine::Support::Config::Definition::Field then
    desc = d.description_value
    desc_str  = desc.respond_to?(:call) ? desc.call : desc
    long_opt = d.long_opt
    args = [d.short_opt, long_opt, desc_str].compact
    case d.__type__
    when :action then
      obj = eval("self", d.__block__.binding)
      (class << obj; self; end).module_eval do
        attr_accessor :option_parser
      end
      obj.option_parser = option_parser
      o.on(*args, &d.__block__)
    when :separator then
      o.separator(d.description)
    else
      case d.type
      when :boolean then
        o.on(*args){d.__parent__.send("#{d.__name__}=", true)}
      when :load_config then
        long_opt << "=VAL"
        o.on(*args){|f| d.__parent__.send("#{d.__name__}=", f) }
      else
        long_opt << "=VAL"
        if d.enum
          desc_str << " must be one of " << (d.enum.join(',').gsub(/\A\[|\]\Z/, ''))
        end
        if default_value = d.default_value
          desc_str << " default: #{default_value.inspect}"
        end
        o.on(*args){|val| d.__parent__.send("#{d.__name__}=", val)}
      end
    end
  else
    raise "Unsupported definition class #{d.class.name}"
  end

end