Class: ActiveMatrix::ChatSession
- Inherits:
-
ApplicationRecord
- Object
- ActiveRecord::Base
- ApplicationRecord
- ActiveMatrix::ChatSession
- Defined in:
- app/models/active_matrix/chat_session.rb
Constant Summary collapse
- MAX_HISTORY_SIZE =
Configuration
20
Class Method Summary collapse
Instance Method Summary collapse
-
#add_message(message_data) ⇒ Object
Add a message to the history.
-
#cache_key ⇒ Object
Cache integration.
-
#prune_history! ⇒ Object
Clear old messages but keep context.
-
#recent_messages(limit = 10) ⇒ Object
Get recent messages.
- #write_to_cache ⇒ Object
Class Method Details
.cleanup_stale! ⇒ Object
72 73 74 |
# File 'app/models/active_matrix/chat_session.rb', line 72 def self.cleanup_stale! stale.destroy_all end |
Instance Method Details
#add_message(message_data) ⇒ Object
Add a message to the history
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'app/models/active_matrix/chat_session.rb', line 22 def () = ['messages'] || [] # Add new message << { 'event_id' => [:event_id], 'sender' => [:sender], 'content' => [:content], 'timestamp' => [:timestamp] || Time.current.to_i } # Keep only recent messages = .last(MAX_HISTORY_SIZE) # Update record self. = { 'messages' => } self. = Time.current self. = .size save! # Update cache write_to_cache end |
#cache_key ⇒ Object
Cache integration
60 61 62 |
# File 'app/models/active_matrix/chat_session.rb', line 60 def cache_key "conversation/#{agent_id}/#{user_id}/#{room_id}" end |
#prune_history! ⇒ Object
Clear old messages but keep context
53 54 55 56 57 |
# File 'app/models/active_matrix/chat_session.rb', line 53 def prune_history! = ['messages'] || [] self. = { 'messages' => .last(5) } save! end |
#recent_messages(limit = 10) ⇒ Object
Get recent messages
47 48 49 50 |
# File 'app/models/active_matrix/chat_session.rb', line 47 def (limit = 10) = ['messages'] || [] .last(limit) end |
#write_to_cache ⇒ Object
64 65 66 67 68 69 70 |
# File 'app/models/active_matrix/chat_session.rb', line 64 def write_to_cache Rails.cache.write(cache_key, { context: context, recent_messages: , last_message_at: }, expires_in: 1.hour) end |