Class: BaseApp
- Inherits:
-
Object
- Object
- BaseApp
- Defined in:
- lib/base_app.rb
Instance Attribute Summary collapse
-
#status ⇒ Object
Returns the value of attribute status.
Class Method Summary collapse
Instance Method Summary collapse
- #command_line_arguments ⇒ Object
- #construct_opts ⇒ Object
- #create_setter(name) ⇒ Object
-
#initialize ⇒ BaseApp
constructor
A new instance of BaseApp.
- #parse_command_line_options ⇒ Object
Constructor Details
#initialize ⇒ BaseApp
Returns a new instance of BaseApp.
7 8 9 10 11 |
# File 'lib/base_app.rb', line 7 def initialize @status = 0 @options = {} @required_opts = [] end |
Instance Attribute Details
#status ⇒ Object
Returns the value of attribute status.
5 6 7 |
# File 'lib/base_app.rb', line 5 def status @status end |
Class Method Details
.main ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/base_app.rb', line 48 def self.main app = self.new app. max_width = app.command_line_arguments.map {|x| x[1].length}.max if app.verbose $stderr.puts "#$0 Parameters:" app.command_line_arguments.each do |opt_spec| short, arg, descr = opt_spec option = arg.gsub(/=$/,'').gsub('-','_') $stderr.printf( " %*s : %s\n", max_width, arg.gsub('=',''), app.send(option.to_sym)) end $stderr.puts "" end app.run exit app.status end |
Instance Method Details
#command_line_arguments ⇒ Object
13 14 15 |
# File 'lib/base_app.rb', line 13 def command_line_arguments [['v','verbose','Be more verbose']] end |
#construct_opts ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/base_app.rb', line 17 def construct_opts opts = OptionParser.new do |opts| command_line_arguments.each do |argspec| short, long, description, required = argspec param_name = long.gsub '=', '' @required_opts << param_name if required create_setter(long) opts.on("-#{short}", "--#{long}", description) do |val| @options[param_name] = val setter = param_name.gsub("-", "_") + "=" self.send(setter,val) end end end end |
#create_setter(name) ⇒ Object
33 34 35 36 |
# File 'lib/base_app.rb', line 33 def create_setter(name) name = name.gsub("-", "_").gsub("=", "") self.class.send(:attr_accessor, name) unless self.respond_to?(name) end |
#parse_command_line_options ⇒ Object
38 39 40 41 42 43 44 45 46 |
# File 'lib/base_app.rb', line 38 def opts = construct_opts opts.parse! @required_opts.each do |name| unless @options[name] raise "Error, required argument '#{name}' must be supplied." end end end |