Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexanderadam/be078c2c4f53bbab25dadd8572555785 to your computer and use it in GitHub Desktop.
Save alexanderadam/be078c2c4f53bbab25dadd8572555785 to your computer and use it in GitHub Desktop.
Crystal JSON vs YAML serialization
require "json"
require "yaml"
require "secure_random"
class SerializableKlass
YAML.mapping({
bool: { type: Bool, nilable: true},
float: { type: Float64, nilable: true},
int: { type: Int32, nilable: true},
str: { type: String, nilable: true}
})
JSON.mapping({
bool: { type: Bool, nilable: true},
float: { type: Float64, nilable: true},
int: { type: Int32, nilable: true},
str: { type: String, nilable: true}
})
RANDOM = Random.new
macro add_to_yml(property)
unless {{property}}.nil?
yaml.nl
yaml << "{{property}}: #{@{{property}}}"
end
end
def initialize(bool : (Bool | Nil) = [RANDOM.next_bool, nil].sample,
str : (String | Nil) = [SecureRandom.hex, nil].sample,
float : (Float64 | Nil) = [RANDOM.next_float, nil].sample,
int : (Int32 | Nil) = [RANDOM.next_int, nil].sample)
@bool = bool
@str = str
@float = float
@int = int
end
def to_yaml(yaml : YAML::Generator)
yaml.indented do
add_to_yml(bool)
add_to_yml(str)
add_to_yml(float)
add_to_yml(int)
end
end
def ==(other)
return false unless other.is_a?(SerializableKlass)
other.bool == bool && \
other.str == str && \
other.float == float && \
other.int == int
end
end
require "spec"
describe SerializableKlass do
it "can be serialized to/from JSON" do
42.times do
object = SerializableKlass.new
SerializableKlass.from_json(object.to_json).should eq(object)
end
end
it "can be serialized to/from YAML" do
42.times do
object = SerializableKlass.new
SerializableKlass.from_yaml(object.to_yaml).should eq(object)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment