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.



44
45
46
47
48
49
50
# File 'lib/h2g_ajaxchat.rb', line 44

def initialize(debug: false)

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

Instance Attribute Details

#messagesObject (readonly)

Returns the value of attribute messages.



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

def messages
  @messages
end

#usersObject (readonly)

Returns the value of attribute users.



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

def users
  @users
end

Instance Method Details

#chatter(req, newmsg = nil) ⇒ Object



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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/h2g_ajaxchat.rb', line 60

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
    @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



52
53
54
# File 'lib/h2g_ajaxchat.rb', line 52

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

#logout(req) ⇒ Object



56
57
58
# File 'lib/h2g_ajaxchat.rb', line 56

def logout(req)
  req.session.clear
end