push_messages.rb 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. module PushMessages
  2. def self.enabled?
  3. return true if Thread.current[:push_messages].class == Array
  4. false
  5. end
  6. def self.init
  7. return true if enabled?
  8. Thread.current[:push_messages] = []
  9. end
  10. def self.send(data)
  11. if !PushMessages.enabled?
  12. Sessions.broadcast(
  13. data[:message],
  14. data[:type],
  15. data[:current_user_id],
  16. )
  17. return true
  18. end
  19. message = { type: 'broadcast', data: data }
  20. Thread.current[:push_messages].push message
  21. end
  22. def self.send_to(user_id, data)
  23. if !PushMessages.enabled?
  24. Sessions.send_to(user_id, data)
  25. return true
  26. end
  27. message = { type: 'send_to', user_id: user_id, data: data }
  28. Thread.current[:push_messages].push message
  29. end
  30. def self.finish
  31. return false if !enabled?
  32. Thread.current[:push_messages].each do |message|
  33. if message[:type] == 'send_to'
  34. Sessions.send_to(message[:user_id], message[:data])
  35. else
  36. Sessions.broadcast(
  37. message[:data][:message],
  38. message[:data][:type],
  39. message[:data][:current_user_id],
  40. )
  41. end
  42. end
  43. Thread.current[:push_messages] = nil
  44. true
  45. end
  46. end