Two nice databases for Ruby

String of glass beads

String of glass beads, ca. 400, Korea

Doing small projects with Ruby, there are two databases I find myself coming back to again and again, so I wanted to mention them here.

YAML::Store

The first is YAML::Store, which is built into Ruby. You’ve had it this whole time! For me, a char­ac­ter­istic use of YAML::Store looks something like this:

require "yaml/store"

db = YAML::Store.new("zine-orders.yaml")

db.transaction do
  unless db[some_order_id]["printed"]
    print_order(some_order_id)
    db[some_order_id]["printed"] = true
  end
end

In addition to its overall simplicity, YAML::Store has two really nice properties.

First, the database is, as advertised, just a YAML file, which means you can view its contents in a text editor and even make changes if you like! Most people reading this post will be familiar with YAML; it’s totally simple, even minimal:

---
order_00001:
  recipient_name: Sherlock Holmes
  shipping_address: 221B Baker Street
  printed: false

I have found the ability to spot-check and edit the database in this way very useful.

Second, even though it’s so simple, YAML::Store still gives you the super­power of wrapping changes in a “transaction,” so if something fails midway through — as it, uh, often does in these little scripts I write, espe­cially as I’m devel­oping them — the changes won’t be committed. In the example above, if my call to print_order(some_order_id) fails, the trans­ac­tion will bomb out and the order’s "printed" field will not be marked true. It’s all very basic, but/and that’s often exactly the level of complexity that I need.

Daybreak

I’m not going to explain this one in detail, because it is very well-explained on its own home page, but I feel like not enough people know about Daybreak, the “simple and very fast key value store” created by program­mers at ProPublica. YAML::Store’s one great weakness is that it’s slow; for my purposes, that’s usually fine, but/and when I need something faster, I turn to Daybreak.

The downside is: you can’t open the database and view its contents manually.

The upside is: it is very fast.

Daybreak and YAML::Store are both single-file databases, so there’s none of the hassle of setting up a database server, connecting to it, etc., etc. For a certain scale of project — which includes basically all of mine — they are really much better choices than MySQL, Redis, or anything like them.

May 2020, Oakland