Class: LibertyBot::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/libertybot/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server, port = 6667) ⇒ Client

Returns a new instance of Client.



32
33
34
35
36
37
38
39
# File 'lib/libertybot/client.rb', line 32

def initialize(server, port = 6667)
  @debugging = false
  @connected = true
  @server = server
  @port = port
  @handlers = []
  @socket = []
end

Instance Attribute Details

#connectedObject (readonly)

Returns the value of attribute connected.



30
31
32
# File 'lib/libertybot/client.rb', line 30

def connected
  @connected
end

#debuggingObject

Returns the value of attribute debugging.



29
30
31
# File 'lib/libertybot/client.rb', line 29

def debugging
  @debugging
end

#portObject (readonly)

Returns the value of attribute port.



30
31
32
# File 'lib/libertybot/client.rb', line 30

def port
  @port
end

#serverObject (readonly)

Returns the value of attribute server.



30
31
32
# File 'lib/libertybot/client.rb', line 30

def server
  @server
end

Instance Method Details

#connectObject



41
42
43
44
45
46
47
48
49
50
# File 'lib/libertybot/client.rb', line 41

def connect
  @connected = true
  @socket = Socket.new(Socket::Constants::AF_INET, Socket::Constants::SOCK_STREAM, 0)
  begin
    @socket.connect(Socket::pack_sockaddr_in(@port, @server))
  rescue Errno::EAFNOSUPPORT
    @socket = Socket.new(Socket::Constants::AF_INET6, Socket::Constants::SOCK_STREAM, 0)
    retry
  end
end

#register(command = nil, &block) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/libertybot/client.rb', line 52

def register(command = nil, &block)
  lambda = nil
  if command
    lambda = lambda do |message|
      block.call(message) if message.command == command.to_s
    end
  else
    lambda = block
  end
  @handlers << lambda
  lambda.object_id
end

#send(message) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/libertybot/client.rb', line 71

def send(message)
  connect unless @socket
  
  if message.is_a? Array
    message.each do |item|
      send(item)
    end
    return
  end
  
  @socket.write(message.to_s)
  puts message.to_s if @debugging
end

#startObject



85
86
87
88
89
90
91
# File 'lib/libertybot/client.rb', line 85

def start
  connect unless @socket
  while true
    message = Message.parse(recv)
    handle(message)
  end
end

#unregister(object_id) ⇒ Object



65
66
67
68
69
# File 'lib/libertybot/client.rb', line 65

def unregister(object_id)
  @handlers.delete_if do |callback|
    callback.object_id == object_id
  end
end