Class: Management::Command

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.allObject



5
6
7
# File 'lib/management/command.rb', line 5

def self.all
  @all ||= []
end

.inherited(subclass) ⇒ Object



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

def self.inherited(subclass)
  all << subclass.new
end

.maxlenObject



13
14
15
# File 'lib/management/command.rb', line 13

def self.maxlen
  all.map(&:command_name).map(&:size).max
end

Instance Method Details

#arg_listObject



29
30
31
32
33
34
35
36
37
38
# File 'lib/management/command.rb', line 29

def arg_list
  fn.parameters.map do |req, name|
    name = '<' + name.to_s.sub(/_names?/, '') + '>'
    case req
    when :opt then '[' + name + ']'
    when :rest then name + ' [...]'
    else name
    end
  end.join(' ')
end

#call_with(args, error_handler) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/management/command.rb', line 51

def call_with(args, error_handler)
  arity = self.true_arity

  error_handler.call "not enough arguments" if args.count < arity.begin
  error_handler.call "too many arguments"   if args.count > arity.end

  fn.call *args
end

#command_nameObject



21
22
23
24
25
26
27
# File 'lib/management/command.rb', line 21

def command_name
  self.class.name.
    split('::').
    drop(1).
    join(":").
    downcase
end

#fnObject



17
18
19
# File 'lib/management/command.rb', line 17

def fn
  method(:run)
end

#help_stringObject



40
41
42
# File 'lib/management/command.rb', line 40

def help_string
  sprintf "  %-#{Command.maxlen + 2}s %s", command_name, arg_list
end

#true_arityObject



44
45
46
47
48
49
# File 'lib/management/command.rb', line 44

def true_arity
  min = fn.parameters.take_while{|req, name| req == :req}.count
  max = fn.parameters.count
  max = Float::INFINITY if max > 0 && fn.parameters.last.first == :rest
  min..max
end