Class: Slnky::Command::Base

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

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBase

Returns a new instance of Base.



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

def initialize
  @commands = self.class.commands
end

Class Attribute Details

.commandsObject (readonly)

Returns the value of attribute commands.



63
64
65
# File 'lib/slnky/command.rb', line 63

def commands
  @commands
end

Class Method Details

.command(name, banner, desc) ⇒ Object



65
66
67
68
# File 'lib/slnky/command.rb', line 65

def command(name, banner, desc)
  @commands ||= [Slnky::Command::Processor.new('help', 'print help', 'help [options]')]
  @commands << Slnky::Command::Processor.new(name, banner, desc)
end

Instance Method Details

#handle(event, data, response = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/slnky/command.rb', line 13

def handle(event, data, response=nil)
  begin
    req = Slnky::Command::Request.new(data)
    res = response || Slnky::Command::Response.new(data.response, name)
    log.response = res
    res.start!

    if event == 'slnky.help.command'
      handle_help(req, res)
    else
      handle_command(req, res)
    end

  rescue => e
    log.error "failed to run command: #{name}: #{data.command}: #{e.message} at #{e.backtrace.first}"
  ensure
    res.done!
    log.response = false
  end
end

#handle_command(req, res) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/slnky/command.rb', line 40

def handle_command(req, res)
  begin
    processor = @commands.select { |c| c.name == req.command }.first
    if processor
      options = processor.process(req.args)
      self.send("handle_#{processor.name}", req, res, options)
    else
      log.error "unknown command: #{req.command}"
    end
  rescue Docopt::Exit => e
    log.info e.message
  end
end

#handle_help(req, res, opts = {}) ⇒ Object



34
35
36
37
38
# File 'lib/slnky/command.rb', line 34

def handle_help(req, res, opts={})
  @commands.each do |command|
    log.info "#{name} #{command.name}: #{command.banner}"
  end
end

#logObject



58
59
60
# File 'lib/slnky/command.rb', line 58

def log
  @log ||= Slnky.log
end

#nameObject



54
55
56
# File 'lib/slnky/command.rb', line 54

def name
  @name ||= self.class.name.split('::')[1].downcase
end