Memcached with Rails 3

30 Aug 2011

I never had a reason to play with memcached and it was on my list of things to learn. Below I will demonstrate an example app very quickly and simply. I’m not doing anything more complicated than simple primitive storing. If you are going to store any objects in memcached, dalli gem will take care of this for you (ymmv).

First let’s create a rails app and an rvm gemset to play in.

rvm use 1.9.2@memcache --create

If you don’t have rails in your global gemset, you can install rails now. I used the 3.1 RC here just to test out 3.1 and memcached at the same time.

gem install rails --pre
gem install dalli

Dalli is written by Mike Perham (awesome guy) and simply wires up Rails.cache to be our memcached server. This is convenient and more standard than creating your own global variable or other configuration.

Next, let’s install memcached if we haven’t already:

brew install memcached
$ memcached -v

You can also start memcached as a service under Mac using the homebrew instructions. I like to leave things in the foreground when I’m first setting them up or grok’ing.

Ok, now we can create our dummy app.

rails new memcache_test

Our dummy rails app is going to have a slow controller action in it. In this case, it could be a row count of a huge database. In your case it could be a slow network call or a result of an expensive SQL operation.

Sometimes you need to transpose data from columns to rows or vice-versa. In the SQL world, this is called a pivot table. Usually this happens when you’re coming from a key-value store and want to turn it into something more structured but it can also happen in poorly designed or legacy databases. The idea is pretty simple, pivot the data from rows into columns. For example, here’s a listing of CDs:

Newer

I got to thinking (that’s another story) about the old Technics set that I had when I was a kid and how useful it would be if I could tear down and build things without having to hacksaw stuff (i.e. like with the Microrax stuff). We had major flooding recently (after an earthquake and a hurricane) and the closed roads funneled me to a toy store. Was this a sign? I’m not sure. All I know is I have a Mindstorms kit now. :)

So I built an Arduino frame using nothing but the parts from the Mindstorms kit (it’s all just Technics parts). It’s pretty sturdy and the little rubber ends hold the board down pretty good. I figure it’s good enough to put on wheels or a quad-ped bot. I don’t know if I’d send it up in the air. I’d probably want to add a few more cross bars in there. Anyway, I did a lot of refactoring (if you could call it that) and I think this design is pretty good. Here’s the money shot with the rest of the build shots so you can copy it. I’m fresh brand-new to the Lego scene so leave some comments if I did something stupid.