Class: MadChatter::Channel

Inherits:
Object
  • Object
show all
Defined in:
lib/mad_chatter/channel.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = nil) ⇒ Channel

Returns a new instance of Channel.



6
7
8
9
10
11
# File 'lib/mad_chatter/channel.rb', line 6

def initialize(name = nil)
  @id = MadChatter.channels.count.to_s
  @name = name
  @users = []
  @message_history = MadChatter::MessageHistory.new
end

Instance Attribute Details

#idObject

Returns the value of attribute id.



4
5
6
# File 'lib/mad_chatter/channel.rb', line 4

def id
  @id
end

#message_historyObject

Returns the value of attribute message_history.



4
5
6
# File 'lib/mad_chatter/channel.rb', line 4

def message_history
  @message_history
end

#nameObject

Returns the value of attribute name.



4
5
6
# File 'lib/mad_chatter/channel.rb', line 4

def name
  @name
end

#usersObject

Returns the value of attribute users.



4
5
6
# File 'lib/mad_chatter/channel.rb', line 4

def users
  @users
end

Instance Method Details

#add_user(user) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/mad_chatter/channel.rb', line 13

def add_user(user)
  @users << user
  send_users_list
  @message_history.all.each do |json|
    user.send(json)
  end
  send_message MadChatter::Message.new('status', "#{user.username} has joined the chatroom")
end

#remove_user(user) ⇒ Object



22
23
24
25
26
27
# File 'lib/mad_chatter/channel.rb', line 22

def remove_user(user)
  if @users.delete(user)
    send_message MadChatter::Message.new('status', "#{user.username} has left the chatroom")
    send_users_list
  end
end

#send_json(json) ⇒ Object



49
50
51
52
53
# File 'lib/mad_chatter/channel.rb', line 49

def send_json(json)
  @users.each do |user|
    user.send(json)
  end
end

#send_message(message) ⇒ Object



42
43
44
45
46
47
# File 'lib/mad_chatter/channel.rb', line 42

def send_message(message)
  message.channel = @id
  json = message.to_json
  send_json(json)
  @message_history.add(json) if message.add_to_history?
end

#send_users_listObject



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mad_chatter/channel.rb', line 29

def send_users_list
  usernames = []
  @users.each do |user|
    usernames << user.username
  end
  json = JSON.generate({
    type: 'users',
    json: usernames,
    channel: @id,
  })
  send_json(json)
end