This website is written in Ruby using the Sinatra framework and hosted with Passenger / Nginx on the Raspberry Pi ( temporarily not on a Pi! ) assisted by Cloudflare and a dash of jsDelivr

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 = 'localhost:11211'

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

		cached = yield
		CACHE.set key, cached, expiry



cache( 'mypage', 300 ) do

	# Some complex page output!


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