Created
October 29, 2011 13:47
-
-
Save mdesjardins/1324475 to your computer and use it in GitHub Desktop.
Ruby increment operators not working like we think they're working?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Stub class acts as a proxy for the memcache Rails cache. Stores key/value pairs in files. | |
class FakeCache | |
def self.write(key,value) | |
File.open(key,'w') { |f| f.write(value) } | |
end | |
def self.read(key) | |
begin | |
File.open(key).each_line{ |s| result = s } | |
result | |
rescue | |
return nil | |
end | |
end | |
end | |
# Based on our Restaurant model | |
class TestOp | |
def self.cache_key=(num) | |
#Rails.cache.write('restaurant_cache_key', num) | |
FakeCache.write('restaurant_cache_key', num) | |
end | |
def self.cache_key | |
#unless r = Rails.cache.read('restaurant_cache_key') | |
unless r = FakeCache.read('restaurant_cache_key') | |
r = rand(10000) | |
FakeCache.write('restaurant_cache_key', r.to_s) | |
end | |
return r.to_i | |
end | |
end | |
# start w/ a clean slate | |
File.delete('restaurant_cache_key') | |
# Try to read a nil cache, increment it, read again. | |
puts TestOp.cache_key | |
TestOp.cache_key += 1 | |
puts TestOp.cache_key | |
# Result | |
# ~/_work/elctech/temp> ruby testop.rb | |
# 130 | |
# 5912 | |
# ~/_work/elctech/temp> ruby testop.rb | |
# 4044 | |
# 9614 | |
# ~/_work/elctech/temp> ruby testop.rb | |
# 8176 | |
# 7017 | |
# ~/_work/elctech/temp> ruby testop.rb | |
# 296 | |
# 5709 | |
# ~/_work/elctech/temp> ruby testop.rb | |
# 2074 | |
# 4293 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment