I’m trying to build some basic object-persistence (save game, load game) into my sandbox app.
I’m using YAML to dump objects to a file, and then I want to recover them. I have two different classes of instantiated objects, and they get written like this, which all seems fine:
---
- !ruby/object:Game::Room
reference: :largecave
name: Large cave
description: a large empty cave
connections:
:west: :smallcave
:south: :waterfall
- !ruby/object:Game::Room
reference: :smallcave
name: Small cave
description: a small cave
connections:
:east: :largecave
- !ruby/object:Game::Room
reference: :waterfall
(... etc)
---
- !ruby/object:Game::GameObject
reference: :key
name: Key
description: A small key
room: :smallcave
- !ruby/object:Game::GameObject
reference: :bowl
(....etc)
The problem comes trying to recover and populate the two different arrays of objects:
YAML.load(datastore.read)
works fine but is only good for one class of object, and I’ve tried the select method, like this, but without success:
@rooms = datastore.select("!ruby/object:Game::Room")
@objects = datastore.select("!ruby/object:Game::GameObject")
As a suggestion for data-usability, I’d recommend creating some methods for your classes to generate hashes of the contents of an object. That way you can store YAML representations of hashes, which are universal, rather than Ruby objects, which are only usable in Ruby, not other languages.
I’d forgo creating multiple documents in your YAML file and would use something like:
Which outputs:
Looking at the data after a round-trip through YAML-land:
You could also take advantage of YAML::Store and do it like:
Which looks like:
YAML::Store will create your YAML file on disk for you:
Which is basically a hash, where
placesandthingsare the keys to the embedded data.Storing the configuration of “Adventure” in a YAML file might become unwieldy, so you might want to look into using something like Sequel and a SQLite database eventually. You could store the data in a common format still, but it’d also be set up for fast random access and wouldn’t need to be contained in memory.