Ruby memcache-client enhancement
Recently I have been refactoring some code so that various computed results are saved in a memcached cache to improve performance.
A common cache idiom is:
- Compute cache key
- look up key in cache
- if value found, return it
- else, run some code to generate the required value
- save the generated value in the cache
- return the value
It's quite awkward to have that code repeated all over your app, so I hit upon the idea
of passing a block to Cache#get() which would be used to compute
the value if the key wasn't found in the cache.
My proof of concept code to add this functionality to the Cache module is:
module Cache
class << self
alias _get get
end
def self.get(key, expiry = 0)
value = _get(key)
if value.nil? && block_given?
value = yield
put(key, value, expiry)
end
value
end
end
If no block is given, it works exactly the same as the original get() method. If a block is given then the block is executed to generate the value if it isn't found in the cache. The value is then stored in the cache and returned.
My code looks nicer now, instead of this:
cache_key = "#{some}/#{vars}"
value = Cache.get cache_key
unless value
value = a_SOAP_call_that_takes_a_few_seconds()
Cache.put cache_key, value, 10.minutes
end
value
I now have this:
Cache.get("#{some}/#{vars}", 10.minutes) do
a_SOAP_call_that_takes_a_few_seconds()
end
I have logged this possible enhancement to the bug tracker for memcache-client.
Fix Ruby on Mac OS X 10.4
Mac OS X 10.4 comes with ruby 1.8.2, it seems to have a problem with OpenSSL which causes switchtower to hang when trying to connect to your server.
You can download the source code to Ruby 1.8.3, compile it and install it, but you’ll start getting weird errors in gem when you try to install some libraries.
The solution turned out to be to compile Ruby slightly differently. You need to pass some flags to configure:
./configure --enable-shared --enable-pthread
After configuring it, makeing it, and running sudo make install, I had what seemed to be a working Ruby installation. It installs to /usr/local/bin which is already in my path. Executing hash -r causes bash to re-scan the path, after which executing ruby -v correctly reports
ruby 1.8.3 (2005-09-21) [powerpc-darwin8.3.0]
After that I installed RubyGems-0.8.11 and the rails and switchtower gems, including all dependencies. The installation worked fine, and so did switchtower when I tested it.
I didn’t even need to remove Apple’s Ruby install.
If you do want to remove Apple’s installation of Ruby, you’ll want to back up and delete the following files and directories:
/usr/bin/erb
/usr/bin/irb
/usr/bin/rdoc
/usr/bin/ri
/usr/bin/ruby
/usr/bin/testrb
/usr/bin/gem
/usr/bin/gem_server
/usr/bin/gemwhich
/usr/bin/rake
/usr/lib/ruby/
/usr/lib/libruby.1.dylib
/usr/lib/libruby.dylib
/usr/share/ri/
Posted in Ruby, Rails | no comments |

