Sliced Software

About

Thomas Mango writes software, has a bulldog, listens to Long Island Hardcore music and eats sandwiches.

He is currently working freelance projects as well as on his own project, Limited Pressing.

Software

PGnJ An intuitive Database Development Environment for Mac OS X.

Mobile LIRR An iPhone optimized Long Island Railroad scheduling application.

Trends An iPhone optimized Twitter Trends application. Get the current trends and their reason for trending on the go (data by What the Trend?).

A better Rails.cache.increment

I started working with Rails.cache.increment and Rails.cache.decrement today but quickly found that it didn’t work as I planned. For example, it seemed that when calling these methods they would return the previous value rather than the newly incremented value. Additionally, if you decided to read directly using Rails.cache.read and the same key, it would always return nil despite being able to call Rails.cache.increment again. Another annoying thing is that if you tried to increment a value that wasn’t in memcached, instead of defaulting to 1, it returned nil. Just all sorts of wacky stuff going on. I decided to just write my own.

Update: click through for the source.

# app/models/util/cache.rb
 
class Util::Cache
  def self.increment(key, amount = 1)
    if (value = Rails.cache.read(key)).nil?
      Rails.cache.write(key, (value = amount))
    else
      Rails.cache.write(key, (value = value + amount))
    end
    
    return value
  end
  
  def self.decrement(key, amount = 1)
    if (value = Rails.cache.read(key)).nil?
      value = 0
    else
      Rails.cache.write(key, (value = value - amount))
    end
    
    return value
  end
end
view raw This Gist brought to you by GitHub.
Looking for really old posts? Until they are here at tumblr, see here!