Module: IRCMachine::Command

Defined in:
lib/ircmachine/command.rb

Class Method Summary collapse

Class Method Details

.cmdsObject



7
8
9
# File 'lib/ircmachine/command.rb', line 7

def cmds
  @cmds ||= {}
end

.defcmd(cmd, *arg_names) ⇒ Object



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
# File 'lib/ircmachine/command.rb', line 28

def defcmd(cmd, *arg_names)
  cmd = cmd.strip.upcase

  klass = Class.new do
    define_method(:initialize) do |prefix = nil, *args|
      @prefix = prefix
      arg_names.zip(args).each { |name, value| instance_variable_set("@#{name}", value) }
    end

    # Create readers for the parameters.
    arg_names.each do |name|
      define_method(name) { instance_variable_get("@#{name}") }
    end

    define_method(:prefix) { instance_variable_get('@prefix') }

    define_method(:to_msg) do
      param_values = arg_names.map { |k| instance_variable_get("@#{k}") }.join(' ')
      IRCMachine::Message.new(@prefix, cmd, param_values)
    end

    define_method(:to_s) { self.to_msg.to_s }
  end

  const_set("#{cmd.capitalize}Command", klass)
  cmds[cmd] = klass
end

.defrcmd(cmd, *arg_names) ⇒ Object

Same as defcmd, but arguments are passed in reverse order. This is to support the WHOIS command, which has an optional parameter in the middle, rather than at the end…



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/ircmachine/command.rb', line 60

def defrcmd(cmd, *arg_names)
  cmd = cmd.strip.upcase

  klass = Class.new do
    define_method(:initialize) do |prefix = nil, *args|
      instance_variable_set('@prefix', prefix)

      arg_names.reverse.zip(args.reverse).each { |name, value| instance_variable_set("@#{name}", value) }
    end

    # Create readers for the parameters.
    arg_names.each do |name|
      define_method(name) { instance_variable_get("@#{name}") }
    end

    define_method(:prefix) { instance_variable_get('@prefix') }

    define_method(:to_msg) do
      param_values = arg_names.reverse.map { |k| instance_variable_get("@#{k}") }.join(' ')

      IRCMachine::Message.new(
        instance_variable_get('@prefix'),
        cmd,
        param_values
      )
    end

    define_method(:to_s) { self.to_msg.to_s }
  end

  const_set("#{cmd.capitalize}Command", klass)
  cmds[cmd] = klass
end

.from_msg(msg) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/ircmachine/command.rb', line 12

def from_msg(msg)
  if (klass = cmds[msg.command]).nil?
    fail ArgumentError, "Unknown command: #{msg.command}"
  else
    klass.new(msg.prefix, *msg.params)
  end
end

.parse(str) ⇒ Object



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

def parse(str)
  if (msg = IRCMachine::Message.parse(str)).nil?
    fail ArgumentError, 'Invalid format for IRC message.'
  else
    from_msg(msg)
  end
end