Skip to content

Instantly share code, notes, and snippets.

@gvaughn
Last active April 29, 2020 07:56
Show Gist options
  • Save gvaughn/2387352 to your computer and use it in GitHub Desktop.
Save gvaughn/2387352 to your computer and use it in GitHub Desktop.
YAML pitfalls

Case 1: Missing Colon

.yml looks like:

  purchases_edit
    cannot_edit: "Purchase cannot be edited after submission"

We can test in irb:

YAML.load('purchases_edit
  cannot_edit: "Purchase cannot be edited after submission"')
 => {"purchases_edit cannot_edit"=>"Purchase cannot be edited after submission"}

The missing colon at the end of 'purchases_edit' has created a valid YAML in which the key is 'purchases_edit cannot_edit'. Yes, keys can have embedded spaces. I told you the YAML spec was permissive. If we were expecting I18n.translate("purchases_edit.cannot_edit") to return a value, we'd be sorely disappointed.

Case 2: Missing Space after Colon

.yml looks like:

  show:
    hold_tight:"Hold tight: we will email you when your order is ready."

We can test in irb:

YAML.load('  show:
  hold_tight:"Hold tight: we will email you when your order is ready."')
 => {"show"=>{"hold_tight:\\"Hold tight"=>"we will email you when your order is ready.\""}} 

As you can see, under the show context, we have a key of "hold_tight:"Hold tight". Yes, Virginia, not only can keys have embedded spaces, but they can have embedded colons and unmatched quotes! I18n.translate("show.hold_tight") will be disappointing. We can have unmatched quotes in the value too. Liberal YAML spec is liberal.

@FranklinChen
Copy link

At work, I specified a YAML format for non-technical people to edit config files, but I'm thinking now that maybe straight JSON is the way to go because YAML is actually much more confusing than JSON.

@gvaughn
Copy link
Author

gvaughn commented Sep 9, 2015

The other big piece I didn't even mention in the gist is that YAML can contain executable code.

@gvaughn
Copy link
Author

gvaughn commented Sep 9, 2015

@FranklinChen JSON is another widely available choice, but I find the braces and quotes confusing for non-technical people. It's not hard to parse a very simple key/value pair format you define for your particular needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment