Simple caching in Rails 3.1

Parting ways with http://alianosbatavia.com 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 = Rails.cache.read(:reservation_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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s