Aliano’s Ristorante

Simple caching in Rails 3.1

Parting ways with has been a lot harder than I thought. Every time I think I’m going to hang it up, I think of something new to add to it.  Recently, I wanted to use simple caching to load blocks of reservations at start up, then refresh those blocks after each successful update of blocks from the admin UI.  Here we’ll talk about reading to and writing from the cache in Rails 3.1.

Writing to the cache

In config/initializers/load_reservations.rb:

require File.dirname(__FILE__) + '/../../lib/reservations_loader.rb'
Rails.cache.write(:reservation_blocks, ReservationsLoader.build_reservations_map)

Reading from the cache
In app/models/reservation.rb:

blocks =

Pretty easy.  I have an observer on ReservationBlocks that refreshes the cache the same way it initially loads it on startup.  This gives me a fast and easy way to display only reservations that are available for the currently selected date on the reservations screen without having to query the database every time a reservation time is requested.