Last active
November 18, 2020 10:33
-
-
Save t-davies/b6fc5d1742c12ec2a69ccb93892e9660 to your computer and use it in GitHub Desktop.
Parses a YAML file with unknown !ruby tags, using js-yaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Type, Schema } from "js-yaml"; | |
const BigDecimal = new Type("!ruby/object:BigDecimal", { | |
kind: "scalar", | |
construct: (data) => { | |
return parseFloat(data.split(":")[1]); | |
}, | |
}); | |
const supportedTags = [BigDecimal]; | |
const supportedTagNames = supportedTags.map((type) => type.tag); | |
const createPassthroughTag = ({ tag, kind }) => new Type(tag, { kind }); | |
const createSchema = (tags) => { | |
return Schema.create([ | |
...supportedTags, | |
...tags | |
.filter(({ tag }) => !supportedTagNames.includes(tag)) | |
.map(createPassthroughTag), | |
]); | |
}; | |
export const createSafeSchema = (message) => { | |
const tags = Array.from(message.matchAll(/!ruby\/[A-Za-z: ]*/g), (m) => m[0]); | |
const uniqueTags = Array.from(new Set(tags)); | |
return createSchema( | |
uniqueTags.map((tag) => ({ | |
tag: tag.replace("\n", "").trim(), | |
kind: tag.endsWith(" ") ? "scalar" : "mapping", | |
})) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment