From 6257dc27b564186c38ab1b86e75c35a3d4aa5573 Mon Sep 17 00:00:00 2001 From: Artem Napolskih Date: Mon, 10 Nov 2014 10:41:06 +0500 Subject: [PATCH] feature(hash_counter): added float mode --- lib/redis_counters/hash_counter.rb | 16 ++++++++++++++-- spec/redis_counters/hash_counter_spec.rb | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/redis_counters/hash_counter.rb b/lib/redis_counters/hash_counter.rb index 5fce069..d46b1e5 100644 --- a/lib/redis_counters/hash_counter.rb +++ b/lib/redis_counters/hash_counter.rb @@ -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 @@ -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 \ No newline at end of file diff --git a/spec/redis_counters/hash_counter_spec.rb b/spec/redis_counters/hash_counter_spec.rb index c2c5573..4160f6c 100644 --- a/spec/redis_counters/hash_counter_spec.rb +++ b/spec/redis_counters/hash_counter_spec.rb @@ -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 \ No newline at end of file