This website was originally written in Ruby and hosted on the Raspberry Pi. It's now archived at GitHub for posterity!

Ruby can be lovely sometimes

To keep strain on my Raspberry Pi to a minimum, this site is memcached via Ruby memcache-client

I created a simple wrapper around the client to cache blocks of output code, it's so terse and elegant that I feel I must share:

require 'memcache'
CACHE = MemCache.new 'localhost:11211'

def cache( key, expiry = 0 )
	
	if cached.nil?

		cached = yield
		CACHE.set key, cached, expiry

	end
	
	cached

end

cache( 'mypage', 300 ) do

	# Some complex page output!
	'hello!'

end

See how it works? Ruby allows a method call to wrap a "block" of code, and the method can yield control to that block when told to do so.

In this case, we check our MemCache for a cached instance of the code output, and where it doesn't exist we yield to the block, capture its output, cache for 5 minutes and return that output. If it's already cached, we simply return the cached version.

« Back to index Posted on 2012-06-20 by