Module: Befog::Commands::Mixins::Command

Included in:
Add, Configure, List, Remove, Run, Start, Stop
Defined in:
lib/befog/commands/mixins/command.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



33
34
35
# File 'lib/befog/commands/mixins/command.rb', line 33

def options
  @options
end

Class Method Details

.included(target) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/befog/commands/mixins/command.rb', line 8

def self.included(target)
  target.module_eval do
    
    class << self 
      
      def command(descriptor=nil)
        descriptor ? (@command = OpenStruct.new(descriptor)) : @command
      end
      
      def option(name,descriptor)
        options << [name,descriptor]
      end
      
      def options ; @options||=[] ; end

      def run(options)
        Befog.show_version if options[:version] or options[:v]
        new(options).run
      end
      
    end
    
  end
end

Instance Method Details

#commandObject



41
42
43
# File 'lib/befog/commands/mixins/command.rb', line 41

def command
  self.class.command
end

#error(message) ⇒ Object

Raises:



77
78
79
# File 'lib/befog/commands/mixins/command.rb', line 77

def error(message)
  raise CLI::Error.new(message)
end

#initialize(_options) ⇒ Object



35
36
37
38
39
# File 'lib/befog/commands/mixins/command.rb', line 35

def initialize(_options)
  safely do
    @options = process_options(_options)
  end
end

#log(message) ⇒ Object



81
82
83
# File 'lib/befog/commands/mixins/command.rb', line 81

def log(message)
  $stdout.puts(message)
end

#process_options(_options) ⇒ Object

TODO: Support multi-line descriptions?



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/befog/commands/mixins/command.rb', line 46

def process_options(_options)
  if (command.default_to_help and _options.empty?) or _options[:help]
    usage
    exit(0)
  end
  self.class.options.each do |name,descriptor|
    short, required, default, type = descriptor.values_at(:short,:required,:default,:type)
    _options[name] ||= (_options[short]||default)
    _options.delete(short)
    if required and not _options[name]
      error("Missing required option --#{name}")
    end
  end
  # TODO: add type conversion
  return _options
end

#usageObject



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/befog/commands/mixins/command.rb', line 63

def usage
  $stderr.puts command.usage
  usage = []
  self.class.options.each do |name,descriptor|
    short, required, default, description = descriptor.values_at(:short,:required,:default,:description)
    required = (required ? "(required) " : "")
    default = (default ? "(default: #{default}) " : "")
    usage << "\t%-3s %-20s\t%-40s" % ["-#{short},", "--#{name} #{name.to_s.upcase}", "#{description} #{required}#{default}"]
  end
  $stderr.puts *(usage.sort)
end