Comandante/Msgpack
An add-on for Comandante for simplifying msgpack reading/writing.
Installation
- Add the dependency to your
shard.yml
:
dependencies:
comandante-msgpack:
github: tghaleb/comandante-msgpack
- Run
shards install
Usage
require "comandante-msgpack"
This is actually a wrapper around msgpack-crsytal.
By default Crystal
types will be serializable, but for custom classes to
be serializable you need to add something like this to your class.
require "msgpack"
class Location
include MessagePack::Serializable
property lat : Float64
property lng : Float64
end
You can either use the reader to write a large object to a file,
Helper.write_msgpack(my_object, file)
Or use in an append mode and append multiple objects, of the same type, to file.
objects.each do |x|
Helper.write_msgpack(x, file, mode: "a")
end
If you need something more complicated than this use msgpack-crsytal directly.
To read one object,
data = Helper.read_msgpack(f, Array(Int32).new)
This will raise an error if you pass the wrong data type or in case the file is empty.
To read multiple objects, for example multiple Arrays from a file,
Helper.read_msgpack(f, Array(Float64).new) do |data|
puts data.inspect
end
module Comandante::Helper
Some helper functions
Class methods
.read_msgpack(file, data)
(file, data)
Reads data from file - first/only object in file
- Asserts file exists
- Raises
MessagePack::EofError
if file is empty - Raises MessagePack::TypeCastError if not the correct type
Note
you pass an object of the desired type
.read_msgpack(file, data, &) : Nil
(file, data, &) : Nil
- Asserts file exists
- Raises MessagePack::TypeCastError if not the correct type
Note
you pass an object of the desired type