Skip to content

Instantly share code, notes, and snippets.

@z64
Last active February 27, 2017 22:11
Show Gist options
  • Save z64/62fdb75d6bc09d3e91b4d0ae3ade0577 to your computer and use it in GitHub Desktop.
Save z64/62fdb75d6bc09d3e91b4d0ae3ade0577 to your computer and use it in GitHub Desktop.
basic string converter macro for crystal
require "json"
require "yaml"
require "./string_converter"
data = {test: "1", value: "3.5"}
json_data = data.to_json
yaml_data = data.to_yaml
class Data
JSON.mapping({
test: {type: Int16?, converter: StringConverter::Int16},
value: {type: Float64?, converter: StringConverter::Float64},
})
YAML.mapping({
test: {type: Int16?, converter: StringConverter::Int16},
value: {type: Float64?, converter: StringConverter::Float64},
})
end
puts Data.from_json(json_data).inspect #=> #<Data:0x84a3e70 @test=1, @value=3.5>
puts Data.from_yaml(yaml_data).inspect #=> #<Data:0x84a3e70 @test=1, @value=3.5>
module StringConverter
{% for typ in [Int16, Int32, Int64, Float32, Float64] %}
class {{typ}}
def self.from_json(parser) : ::{{typ}} | Nil
str = parser.read_string
::{{typ}}.new str
rescue ArgumentError
nil
end
def self.from_yaml(parser) : ::{{typ}} | Nil
str = parser.read_raw
::{{typ}}.new str
rescue ArgumentError
nil
end
end
{% end %}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment