Skip to content

Instantly share code, notes, and snippets.

@t-davies
Last active November 18, 2020 10:33
Show Gist options
  • Save t-davies/b6fc5d1742c12ec2a69ccb93892e9660 to your computer and use it in GitHub Desktop.
Save t-davies/b6fc5d1742c12ec2a69ccb93892e9660 to your computer and use it in GitHub Desktop.
Parses a YAML file with unknown !ruby tags, using js-yaml
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