Skip to content

Commit

Permalink
Fix context updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander committed Jan 20, 2024
1 parent 9011faa commit e3a3346
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 6 deletions.
10 changes: 5 additions & 5 deletions app/models/chat.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@ def generate_story
def context(ids = nil)
size = Rails.configuration.secrets[:context_size]
current = RedisService.lrange(redis_context_path, 0, size).map(&:to_i)
return current.shuffle if ids.nil?
return current if ids.nil?

uniq_ids = ids.uniq
current -= uniq_ids
current.unshift(*uniq_ids)
uniq_ids = ids.map(&:to_i).uniq
current = (uniq_ids | current).compact_blank.first(size)
RedisService.multi do |r|
r.del(redis_context_path)
r.lpush(redis_context_path, current.first(size))
r.lpush(redis_context_path, current)
end
current
end

private
Expand Down
2 changes: 1 addition & 1 deletion app/services/redis_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ def connection
@connection ||= Redis.new(Rails.configuration.secrets[:cache_redis])
end

delegate :multi, :lrange, :set, :get, :incr, :decr, to: :connection
delegate :del, :ltrim, :lpush, :rpush, :multi, :lrange, :set, :get, :incr, :decr, to: :connection
end
end
51 changes: 51 additions & 0 deletions spec/models/chat_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,57 @@
expect(chat).to be_valid
end

describe '#context' do
subject(:method_call) { chat.context(new_ids) }

let(:redis_key) { "chat_context/#{chat.id}" }
let(:old_ids) { %w[4 5 6 2] }

after { RedisService.del(redis_key) }

context 'when new ids absend' do
let(:new_ids) { nil }

context 'when context is empty' do
it 'returns empty array' do
expect(method_call).to eq []
end
end

context 'when context is not empty' do
before { RedisService.lpush(redis_key, old_ids) }

it 'returns empty array' do
expect(method_call).to match_array old_ids.map(&:to_i)
end
end
end

context 'when new ids present' do
let(:new_ids) { %w[1 2 3 4] }

context 'when context is empty' do
before { RedisService.del(redis_key) }

it 'adds new context' do
method_call
result = RedisService.lrange(redis_key, 0, 50)
expect(result).to match_array new_ids
end
end

context 'when context has smth' do
before { RedisService.lpush(redis_key, old_ids) }

it 'merges context' do
method_call
result = RedisService.lrange(redis_key, 0, 50)
expect(result).to match_array(new_ids | old_ids)
end
end
end
end

describe '#choose_winner!' do
subject(:method_call) { chat.choose_winner! }

Expand Down

0 comments on commit e3a3346

Please sign in to comment.