lib/slack/real_time/client.rb in slack-ruby-client-0.5.4 vs lib/slack/real_time/client.rb in slack-ruby-client-0.6.0
- old
+ new
@@ -7,25 +7,34 @@
include Api::MessageId
include Api::Ping
include Api::Message
include Api::Typing
+ @events = {}
+
+ class << self
+ attr_accessor :events
+ end
+
attr_accessor :web_client
+ attr_accessor :store
+ attr_accessor :url
attr_accessor(*Config::ATTRIBUTES)
def initialize(options = {})
@callbacks = Hash.new { |h, k| h[k] = [] }
Slack::RealTime::Config::ATTRIBUTES.each do |key|
send("#{key}=", options[key] || Slack::RealTime.config.send(key))
end
+ @store_class = options.key?(:store_class) ? options[:store_class] : Slack::RealTime::Store
@token ||= Slack.config.token
@web_client = Slack::Web::Client.new(token: token)
end
- [:url, :team, :self, :users, :channels, :groups, :ims, :bots].each do |attr|
- define_method attr do
- @options[attr.to_s] if @options
+ [:users, :self, :channels, :team, :teams, :groups, :ims, :bots].each do |store_method|
+ define_method store_method do
+ store.send(store_method) if store
end
end
def on(type, &block)
type = type.to_s
@@ -69,13 +78,15 @@
protected
# @return [Slack::RealTime::Socket]
def build_socket
fail ClientAlreadyStartedError if started?
- @options = web_client.rtm_start
-
- socket_class.new(@options.fetch('url'), socket_options)
+ start = web_client.rtm_start(start_options)
+ data = Slack::Messages::Message.new(start)
+ @url = data.url
+ @store = @store_class.new(data) if @store_class
+ socket_class.new(@url, socket_options)
end
def socket_options
socket_options = {}
socket_options[:ping] = websocket_ping if websocket_ping
@@ -135,13 +146,24 @@
end
end
def dispatch(event)
return false unless event.data
- data = JSON.parse(event.data)
- type = data['type']
+ data = Slack::Messages::Message.new(JSON.parse(event.data))
+ type = data.type
return false unless type
- callbacks = self.callbacks[type.to_s]
+ type = type.to_s
+ run_handlers(type, data) if @store
+ run_callbacks(type, data)
+ end
+
+ def run_handlers(type, data)
+ handler = Slack::RealTime::Client.events[type]
+ handler.call(self, data) if handler
+ end
+
+ def run_callbacks(type, data)
+ callbacks = self.callbacks[type]
return false unless callbacks
callbacks.each do |c|
c.call(data)
end
true