Class: MiniBot::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/minibot/server.rb

Constant Summary collapse

REPLY_RE =
/:\S+ (\d{3}) \S+ :?(.+)/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.connect(server, port) ⇒ Object



5
6
7
8
9
# File 'lib/minibot/server.rb', line 5

def self.connect(server, port)
  s = new(server, port)
  s.connect
  s
end

Instance Method Details

#connectObject



11
12
13
# File 'lib/minibot/server.rb', line 11

def connect
  @socket = TCPSocket.new(@server, @port)
end

#disconnectObject



78
79
80
# File 'lib/minibot/server.rb', line 78

def disconnect
  @socket.close if @socket
end

#extract(regexp) ⇒ Object



74
75
76
# File 'lib/minibot/server.rb', line 74

def extract(regexp)

end

#match_code(code, message) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/minibot/server.rb', line 24

def match_code(code, message)
  if (match = reply?(message)) && match[1] == code
    match[1, 2]
  else
    nil
  end
end

#readObject



15
16
17
18
19
20
21
22
# File 'lib/minibot/server.rb', line 15

def read
  if @messages.first && message_complete?(@messages.first)
    to_message(@messages.shift)
  else
    read_messages
    read
  end
end

#write(msg, *replies) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/minibot/server.rb', line 32

def write(msg, *replies)
  @socket.print "#{msg}\r\n"

  unless replies.empty?
    index = 0
    matches, messages = catch :halted do
      loop do
        index, message = next_message(index)
        replies.each do |r|
          case r
          when String
            if match = /:\S+ (#{r}) \S+ :?(.+)/.match(message)
              throw :halted, [[ match ], [ message ]]
            end
          when Array
            matched = []
            messages = []
            r.each do |ri|
              if match = /:\S+ (#{ri}) \S+ :?(.+)/.match(message)
                matched << match
                messages << message
                index, message = next_message(index)
              elsif !matched.empty?
                index -= matched.length
                message = matched.first
                break
              end
            end

            throw :halted, [matched, messages] unless matched.empty?
          else
            raise ArgumentError, "Unknown reply argument type: #{r.inspect}", caller
          end
        end
      end
    end

    messages.each { |m| delete_message(m) }
    matches.each { |m| yield m[1, 2] }
  end
end