Class: ChatCore

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(debug: false) ⇒ ChatCore

Returns a new instance of ChatCore.



29
30
31
32
33
34
35
# File 'lib/h2g_ajaxchat.rb', line 29

def initialize(debug: false)

  @debug = debug
  @messages = []
  @count = 0
  @users = {}
end

Instance Attribute Details

#messagesObject (readonly)

Returns the value of attribute messages.



27
28
29
# File 'lib/h2g_ajaxchat.rb', line 27

def messages
  @messages
end

#usersObject (readonly)

Returns the value of attribute users.



27
28
29
# File 'lib/h2g_ajaxchat.rb', line 27

def users
  @users
end

Instance Method Details

#chatter(req, newmsg = nil) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/h2g_ajaxchat.rb', line 45

def chatter(req, newmsg=nil)

  @session = req.session
  append_message(newmsg) if newmsg
  
  return '' if @messages.empty?

  c = @session[:last_id]


  pos = if c then

    last_msg = @messages.find {|x| x.object_id.to_i == c}            
    last_msg ? @messages.index(last_msg)  + 1 : @messages.length - 1

  else

    return '' unless newmsg
    puts '_messages: ' + @messages.inspect
    @messages.length - 1
  end


  if @debug then
    puts 'pos: ' + pos.inspect
    puts '@messages: ' + @messages.inspect
  end    
  
  
  @session[:last_id] = @messages.last.object_id.to_i

  a = @messages[pos..-1].map do |t, id, u, msg|
  
    if block_given? then
      
      yield(t, id, u, msg)
      
    else
      
      s = "user%s: %s" % [id, msg]
      
      [t.strftime("%H:%M:%S"), s].join(' ')
    end
    
  end
                
  a.join("\n")

  
end

#login(req, username) ⇒ Object



37
38
39
# File 'lib/h2g_ajaxchat.rb', line 37

def (req, username)
  req.session[:username] = username
end

#logout(req) ⇒ Object



41
42
43
# File 'lib/h2g_ajaxchat.rb', line 41

def logout(req)
  req.session.clear
end