Module: Polygonio::Websocket::Connection

Defined in:
lib/polygonio/websocket/client.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#urlObject

Returns the value of attribute url.



6
7
8
# File 'lib/polygonio/websocket/client.rb', line 6

def url
  @url
end

Class Method Details

.connect(api_key, url, channels, args = {}, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/polygonio/websocket/client.rb', line 8

def self.connect(api_key, url, channels, args = {}, &block)
  raise "no onmessage callback block given" unless block_given?

  uri = URI.parse(url)
  args[:api_key] = api_key
  args[:channels] = channels
  args[:on_message] = block
  EM.connect(uri.host, 443, self, args) do |conn|
    conn.url = url
  end
end

Instance Method Details

#connection_completedObject



27
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
# File 'lib/polygonio/websocket/client.rb', line 27

def connection_completed
  @driver = WebSocket::Driver.client(self)
  @driver.add_extension(PermessageDeflate)

  uri = URI.parse(@url)
  start_tls(sni_hostname: uri.host)

  @driver.on(:open) do |_event|
    msg = dump({ action: "auth", params: @api_key })
    @driver.text(msg)
  end

  @driver.on(:message) do |msg|
    p [:message, msg.data] if @debug

    events = Oj.load(msg.data, symbol_keys: true).map do |event|
      to_event(event)
    end

    status_events = events.select { |e| e.is_a? WebsocketEvent }
    status_events.each do |event|
      msg = handle_status_event(event)
      @driver.text(msg) if msg
    end

    @on_message.call(events) if status_events.length.zero?
  end

  @driver.on(:close) { |event| finalize(event) }

  @driver.start
end

#finalize(event) ⇒ Object



68
69
70
71
# File 'lib/polygonio/websocket/client.rb', line 68

def finalize(event)
  p [:close, event.code, event.reason] if @debug
  close_connection
end

#initialize(args) ⇒ Object



20
21
22
23
24
25
# File 'lib/polygonio/websocket/client.rb', line 20

def initialize(args)
  @api_key = args.fetch(:api_key)
  @channels = args.fetch(:channels)
  @on_message = args.fetch(:on_message)
  @debug = args.fetch(:debug) { false }
end

#receive_data(data) ⇒ Object



60
61
62
# File 'lib/polygonio/websocket/client.rb', line 60

def receive_data(data)
  @driver.parse(data)
end

#subscribe(channels) ⇒ Object



73
74
75
# File 'lib/polygonio/websocket/client.rb', line 73

def subscribe(channels)
  dump({ action: "subscribe", params: channels })
end

#write(data) ⇒ Object



64
65
66
# File 'lib/polygonio/websocket/client.rb', line 64

def write(data)
  send_data(data)
end