Class: Slacks::Driver

Inherits:
Object
  • Object
show all
Defined in:
lib/slacks/driver.rb

Constant Summary collapse

VALID =
[:open, :message, :error].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDriver

Returns a new instance of Driver.



11
12
13
14
15
# File 'lib/slacks/driver.rb', line 11

def initialize
  @has_been_init = false
  @stop = false
  @callbacks = {}
end

Instance Attribute Details

#stopObject

Returns the value of attribute stop.



9
10
11
# File 'lib/slacks/driver.rb', line 9

def stop
  @stop
end

Instance Method Details

#connect_to(url) ⇒ Object

This init has been delayed because the SSL handshake is a blocking and expensive call



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
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/slacks/driver.rb', line 28

def connect_to(url)
  raise "Already been init" if @has_been_init
  url = URI(url)
  raise ArgumentError.new ":url must be a valid websocket secure url!" unless url.scheme == "wss"

  @socket = OpenSSL::SSL::SSLSocket.new(TCPSocket.new url.host, 443)
  socket.connect # costly and blocking !

  internalWrapper = (Struct.new :url, :socket do
    def write(*args)
      self.socket.write(*args)
    end
  end).new url.to_s, socket

  # this, also, is costly and blocking
  @driver = WebSocket::Driver.client internalWrapper
  driver.on :open do
    @connected = true
    unless callbacks[:open].nil?
      callbacks[:open].call
    end
  end

  driver.on :error do |event|
    @connected = false
    unless callbacks[:error].nil?
      callbacks[:error].call event
    end
  end

  driver.on :message do |event|
    data = MultiJson.load event.data
    unless callbacks[:message].nil?
      callbacks[:message].call data
    end
  end

  driver.start
  @has_been_init = true
end

#connected?Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/slacks/driver.rb', line 77

def connected?
  @connected || false
end

#inner_loopObject

All the polling work is done here



82
83
84
85
86
87
# File 'lib/slacks/driver.rb', line 82

def inner_loop
  return if @stop

  data = @socket.readpartial 4096
  driver.parse data unless data.nil? or data.empty?
end

#main_loopObject



89
90
91
92
93
# File 'lib/slacks/driver.rb', line 89

def main_loop
  loop do
    inner_loop
  end
end

#on(type, &block) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/slacks/driver.rb', line 18

def on(type, &block)
  unless VALID.include? type
    raise ArgumentError.new "Client#on accept one of #{VALID.inspect}"
  end

  callbacks[type] = block
end

#pingObject



73
74
75
# File 'lib/slacks/driver.rb', line 73

def ping
  @driver.ping
end

#write(message) ⇒ Object



69
70
71
# File 'lib/slacks/driver.rb', line 69

def write(message)
  @driver.text(message)
end