Skip to content

Commit a96aaa4

Browse files
committed
Publish post "Ruby Symbols in YAML"
1 parent 026de83 commit a96aaa4

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
title: Ruby Symbols in YAML
3+
date: 2020-10-13 23:00:00 +0200
4+
categories: ruby yaml
5+
---
6+
7+
JSON is nice and simple. Parsing
8+
9+
```json
10+
{
11+
"ent_search": {
12+
"listen_host": "::0"
13+
}
14+
}
15+
```
16+
17+
with `JSON.parse(s)` would return `{"ent_search"=>{"listen_host"=>"::0"}}` as expected.
18+
19+
Parsing YAML is not as simple. What would parsing
20+
21+
```yaml
22+
ent_search:
23+
listen_host: ::0
24+
```
25+
26+
return?
27+
28+
## YAML.load
29+
30+
`YAML.load(s)` returns `{"ent_search"=>{"listen_host"=>:":0"}}`.
31+
32+
What is the difference? `YAML.load(s).dig("ent_search", "listen_host")` is a (Ruby) Symbol, in this case with the value `:":0"`.
33+
34+
## YAML.safe_load
35+
36+
`YAML.safe_load(s)` on the other hand, which is what you should use when parsing YAML from users, will raise an exception:
37+
38+
```
39+
~/.rbenv/versions/2.5.8/lib/ruby/2.5.0/psych/class_loader.rb:97:in `find':
40+
Tried to load unspecified class: Symbol (Psych::DisallowedClass)
41+
```
42+
43+
## Now what?
44+
45+
For now, I think the simplest option is to use `YAML.safe_load` and quote values starting with a semicolon:
46+
47+
```yaml
48+
ent_search:
49+
listen_host: "::0"
50+
```
51+
52+
But I would like there to exist a `YAML.json_load` method (with a better name) that would support the unquoted variant. Perhaps that's something to look into and propose for [ruby/psych](https://github.com/ruby/psych).

0 commit comments

Comments
 (0)