Two nice databases for Ruby

String of glass beads

String of glass beads, ca. 400, Korea

Doing small projects with Ruby, there are two data­bases I find myself coming back to again and again, so I wanted to men­tion 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 some­thing 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 addi­tion to its overall simplicity, YAML::Store has two really nice properties.

First, the data­base is, as advertised, just a YAML file, which means you can view its con­tents 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 data­base in this way very useful.

Second, even though it’s so simple, YAML::Store still gives you the super­power of wrap­ping changes in a “trans­ac­tion,” so if some­thing 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 com­plexity 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 Day­break, the “simple and very fast key value store” cre­ated by pro­gram­mers at ProPublica. YAML::Store’s one great weak­ness is that it’s slow; for my purposes, that’s usu­ally fine, but/and when I need some­thing faster, I turn to Day­break.

The down­side is: you can’t open the data­base and view its con­tents manually.

The upside is: it is very fast.

Day­break and YAML::Store are both single-file data­bases, so there’s none of the hassle of set­ting up a data­base server, con­necting to it, etc., etc. For a cer­tain scale of project — which includes basi­cally all of mine — they are really much better choices than MySQL, Redis, or any­thing like them.

May 2020, Oak­land