Skip to content

Commit

Permalink
feature(hash_counter): added float mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Napolskih committed Nov 10, 2014
1 parent 48deb40 commit 6257dc2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/redis_counters/hash_counter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class HashCounter < BaseCounter
protected

def process_value
redis.hincrby(key, field, 1)
redis.hincrbyfloat(key, field, params.fetch(:value, 1.0))
end

def field
Expand Down Expand Up @@ -48,11 +48,23 @@ def group_keys
def partition_data(cluster, partition)
keys = group_keys.dup << :value
redis.hgetall(key(partition, cluster)).inject(Array.new) do |result, (key, value)|
values = key.split(value_delimiter, -1) << value.to_i
values = key.split(value_delimiter, -1) << format_value(value)
values = values.from(1) unless group_keys.present?
result << Hash[keys.zip(values)].with_indifferent_access
end
end

def format_value(value)
if float_mode?
value.to_f
else
value.to_i
end
end

def float_mode?
@float_mode ||= options.fetch(:float_mode, false)
end
end

end
14 changes: 14 additions & 0 deletions spec/redis_counters/hash_counter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -445,4 +445,18 @@
it { expect(counter.data.third[:param3]).to eq '21:54' }
it { expect(counter.data.third[:value]).to eq 3 }
end

context 'when check custom increment' do
let(:options) { {
:counter_name => :test_counter,
:field_name => :test_field
} }

before { value.times { counter.process(:value => 0.2) } }

it { expect(redis.keys('*')).to have(1).key }
it { expect(redis.keys('*').first).to eq 'test_counter' }
it { expect(redis.hexists('test_counter', 'test_field')).to be_true }
it { expect(redis.hget('test_counter', 'test_field').to_f).to be_within(0.001).of value*0.2.to_f }
end
end

0 comments on commit 6257dc2

Please sign in to comment.