1 min read

TIL: Ruby Has a Built-in Persistance Database

Did you know Ruby has a built-in database?

Did you know that Ruby has a built-in database as part of the standard library?

PStore is a file-backed persistent store based on a Hash with transactional semantics.

require 'pstore'

db = PStore.new('mydatabase.pstore')

This will load the mydatabase.pstore file if it exists or create a new one if it doesn't (though it won't exist on the filesystem until it is written to).

Both writing and reading to the database must be done inside a transaction:

db.transaction do
  db[:names] = {}
  db[:names][:given] = 'Billy'
  db[:names][:family] = 'Ruffian'
end

given_name = db.transaction { db[:names][:given] }
# "Billy"

Useful for persistent configuration perhaps. Under the covers, Ruby is using marshal to write a binary serialised version to the file.

More useful is it's subclass, the YAML::Store:

require 'yaml/store'

db = YAML::Store.new('mydatabase.yml')

This generates a nice, well-formed YAML document which is human-readable.

---
:names:
  :given: Billy
  :family: Ruffian