Skip to content

Instantly share code, notes, and snippets.

@kopylovvlad
Last active April 20, 2019 13:42
Show Gist options
  • Save kopylovvlad/959593f00f7e2c2ddfc76052cfdb758b to your computer and use it in GitHub Desktop.
Save kopylovvlad/959593f00f7e2c2ddfc76052cfdb758b to your computer and use it in GitHub Desktop.
require_relative './event_emitter_core'
# class for users
class User
attr_reader :first_name
def initialize(first_name)
@first_name = first_name
end
end
# service object for notification about new messages
class Notificator
def self.call(message, user)
# notify user about new message
puts "new message '#{message}' for user #{user.first_name}"
end
end
# class for chats
class Chat
include EventEmitterCore
def initialize(title, creator)
@title = title
@messages = []
on(:new_message)
add_subscriber(creator)
end
# to add a subscriber to the chat
def add_subscriber(user)
notify_user = lambda do |event_name, chat_object|
Notificator.call(chat_object.last_message, user)
end
subscribe(:new_message, notify_user)
end
# to delete a subscriber from the chat
def del_subscriber(user, hander_id)
unsubscribe(:new_message, hander_id)
new_message("#{user.first_name} left the chat", nil)
end
# to add new messages to the chat
def new_message(message, user)
@messages << { text: message, from: user&.first_name }
emit(:new_message)
end
# to get the last message
def last_message
@messages.last[:text]
end
end
# user Sasha create new chat
sasha = User.new('sasha')
chat = Chat.new("invitation for Sasha's birthday", sasha)
chat.new_message('test', sasha)
# users Ivan and Vova subscribe to the chat
ivan = User.new('ivan')
vova = User.new('vova')
ivan_handler_id = chat.add_subscriber(ivan)
vova_handler_id = chat.add_subscriber(vova)
# Sasha write a message
chat.new_message('hello, everyone. I invite you to my birthday party', sasha)
# unfortunately, Vova leave the chat
chat.del_subscriber(vova, vova_handler_id)
chat.new_message('Ohhh, Vova left the chat :(', sasha)
#### output is
# new message 'test' for user sasha
# new message 'hello, everyone. I invite you to my birthday party' for user sasha
# new message 'hello, everyone. I invite you to my birthday party' for user ivan
# new message 'hello, everyone. I invite you to my birthday party' for user vova
# new message 'vova left the chat' for user sasha
# new message 'vova left the chat' for user ivan
# new message 'Ohhh, Vova left the chat :(' for user sasha
# new message 'Ohhh, Vova left the chat :(' for user ivan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment