Skip to content

Commit

Permalink
Fix hset for Array of Key / Value Pairs (#312)
Browse files Browse the repository at this point in the history
Fixes #310

This resolves an issue where `Redis` and `MockRedis` were storing values
slightly differently:

## With Redis:
```ruby
require 'redis'
redis = Redis.new

hash = {:name=>"job", :namespace=>"default", :klass=>"Job"}
redis.hset("key", hash.flatten)

redis.hgetall("key")
=> {"name"=>"job", "namespace"=>"default", "klass"=>"Job"}
```

## With MockRedis (with this change):
```ruby
require 'mock_redis'
mock_redis = MockRedis.new

hash = {:name=>"job", :namespace=>"default", :klass=>"Job"}
mock_redis.hset("key", hash.flatten)

mock_redis.hgetall("key")
=> {"name"=>"job", "namespace"=>"default", "klass"=>"Job"}
```
  • Loading branch information
jvanderen1 authored Nov 14, 2024
1 parent 30eb1bc commit b242659
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/mock_redis/hash_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def hscan_each(key, opts = {}, &block)

def hset(key, *args)
added = 0
args.flatten!(1)
with_hash_at(key) do |hash|
if args.length == 1 && args[0].is_a?(Hash)
args = args[0].to_a.flatten
Expand Down
12 changes: 12 additions & 0 deletions spec/commands/hset_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,17 @@
expect(@redises.hset(@key, { 'k1' => 'v1', 'k2' => 'v2' })).to eq(2)
end

it 'stores array values correctly' do
@redises.hset(@key, %w[k1 v1 k2 v2])
expect(@redises.hget(@key, 'k1')).to eq('v1')
expect(@redises.hget(@key, 'k2')).to eq('v2')
end

it 'stores multiple arguments correctly' do
@redises.hset(@key, 'k1', 'v1', 'k2', 'v2')
expect(@redises.hget(@key, 'k1')).to eq('v1')
expect(@redises.hget(@key, 'k2')).to eq('v2')
end

it_should_behave_like 'a hash-only command'
end

0 comments on commit b242659

Please sign in to comment.