Class: RailsSpotlight::Channels::SpotlightChannel

Inherits:
ActionCable::Channel::Base
  • Object
show all
Defined in:
lib/rails_spotlight/channels/spotlight_channel.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.broadcast(attrs = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rails_spotlight/channels/spotlight_channel.rb', line 9

def self.broadcast(attrs = {})
  broadcasting = ::RailsSpotlight::Channels::SPOTLIGHT_CHANNEL
  message = {
    type: attrs[:type],
    code: attrs[:code] || 'ok',
    project: ::RailsSpotlight.config.project_name,
    version: ::RailsSpotlight::VERSION,
    payload: attrs[:payload] || {}
  }
  coder = ::ActiveSupport::JSON
  encoded = coder ? coder.encode(message) : message
  ActionCable.server.pubsub.broadcast(broadcasting, encoded)
  # We do not use the following code because it is triggering logs and can cause an infinite loop
  # ActionCable.server.broadcast(
  #   ::RailsSpotlight::Channels::SPOTLIGHT_CHANNEL,
  #   {
  #     type: attrs[:type],
  #     code: attrs[:code] || 'ok',
  #     project: ::RailsSpotlight.config.project_name,
  #     version: ::RailsSpotlight::VERSION,
  #     payload: attrs[:payload] || {}
  #   }
  # )
rescue StandardError => e
  RailsSpotlight.config.logger.fatal("#{e.message}\n #{e.backtrace.join("\n ")}")
end

Instance Method Details

#receive(data) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/rails_spotlight/channels/spotlight_channel.rb', line 45

def receive(data)
  return publish({ message: 'Unknown type of request', code: :unknown_type, type: :error }) unless Handlers::TYPES.include?(data['type'])

  result = Handlers.handle(data)
  publish({ payload: result[:payload], code: result[:code] || :ok, type: data['type'] }) if result[:payload]
rescue ::RailsSpotlight::Channels::Handlers::ResponseError => e
  publish({ message: e.message, code: e.code, type: :error })
end

#subscribedObject



36
37
38
39
# File 'lib/rails_spotlight/channels/spotlight_channel.rb', line 36

def subscribed
  stream_from ::RailsSpotlight::Channels::SPOTLIGHT_CHANNEL
  publish({ message: "Your #{project} project is now connected to the spotlight channel.", code: :connected, type: :info })
end

#unsubscribedObject



41
42
43
# File 'lib/rails_spotlight/channels/spotlight_channel.rb', line 41

def unsubscribed
  # Any cleanup needed when channel is unsubscribed
end