Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make custom tags easier #86

Merged
merged 8 commits into from
Feb 14, 2019
Merged

Make custom tags easier #86

merged 8 commits into from
Feb 14, 2019

Conversation

eemeli
Copy link
Owner

@eemeli eemeli commented Feb 8, 2019

This is another continuation of #77, #79, and #80, and replaces some of the solutions previously implemented. Specifically, this PR is doing three things:

  1. Deprecate the class attribute of tags, replacing it with the more generic identify(value).
  2. Turn the string stringifier into a generic scalar stringifier, fallback to it by default, and export it as stringify() from yaml/schema.
  3. Improve the documentation on writing custom tags.

In total, this means that e.g. RegExp and shared Symbol tags could now be implemented as:

import { stringify } from 'yaml/schema'

const regexp = {
  identify: value => value instanceof RegExp,
  tag: '!re',
  resolve(doc, cst) {
    const match = cst.strValue.match(/^\/([\s\S]+)\/([gimuy]*)$/)
    return new RegExp(match[1], match[2])
  }
}

const sharedSymbol = {
  identify: value => value.constructor === Symbol,
  tag: '!symbol/shared',
  resolve: (doc, cst) => Symbol.for(cst.strValue),
  stringify(item, ctx, onComment, onChompKeep) {
    const key = Symbol.keyFor(item.value)
    if (key === undefined)
      throw new Error('Only shared symbols are supported')
    return stringify({ value: key }, ctx, onComment, onChompKeep)
  }
}

@eemeli
Copy link
Owner Author

eemeli commented Feb 9, 2019

Rebased on top of master.

@isaacs Note that this PR removes the obj.constructor === t.class check that #79 introduced.

@isaacs
Copy link
Contributor

isaacs commented Feb 11, 2019

I think this is a better API for custom tags.

@eemeli eemeli merged commit 53d80e6 into master Feb 14, 2019
@eemeli eemeli deleted the tag-id branch February 14, 2019 13:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants