This project is archived and is in readonly mode.

#1186 ✓resolved
Doug Barth

Increment/decrement semantics vary between Rails.cache stores

Reported by Doug Barth | October 7th, 2008 @ 05:28 PM

This issue was discussed in more detail on the Rails Core mailing list. http://groups.google.com/group/r...

Essentially, each cache store has different semantics for incrementing & decrementing counters in the cache. The desired semantics can be expressed with the following test cases.


def test_increment
  @cache.write('foo', 1)
  assert_equal 1, @cache.read('foo')
  assert_equal 2, @cache.increment('foo')
  assert_equal 2, @cache.read('foo')
  assert_equal 3, @cache.increment('foo')
  assert_equal 3, @cache.read('foo')
end

def test_decrement
  @cache.write('foo', 3)
  assert_equal 3, @cache.read('foo')
  assert_equal 2, @cache.decrement('foo')
  assert_equal 2, @cache.read('foo')
  assert_equal 1, @cache.decrement('foo')
  assert_equal 1, @cache.read('foo')
end

Unfortunately, due to MemCache's requirement that counter data be stored in raw format, that syntax needs to be modified to following if the MemCache store is to be supported. This style, while ugly, will still work across all stores.


def test_increment
  @cache.write('foo', 1, :raw => true)
  assert_equal 1, @cache.read('foo', :raw => true).to_i
  assert_equal 2, @cache.increment('foo')
  assert_equal 2, @cache.read('foo', :raw => true).to_i
  assert_equal 3, @cache.increment('foo')
  assert_equal 3, @cache.read('foo', :raw => true).to_i
end

def test_decrement
  @cache.write('foo', 3, :raw => true)
  assert_equal 3, @cache.read('foo', :raw => true).to_i
  assert_equal 2, @cache.decrement('foo')
  assert_equal 2, @cache.read('foo', :raw => true).to_i
  assert_equal 1, @cache.decrement('foo')
  assert_equal 1, @cache.read('foo', :raw => true).to_i
end

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages