Skip to content

Commit 361da07

Browse files
committed
Add YAML support
1 parent 6cc1b27 commit 361da07

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,22 @@ example.to_json
117117
# => "{\"id\":\"aWgEPTl1tmebfsQzFP4bxwgy80V\"}"
118118
```
119119

120+
### YAML
121+
122+
```crystal
123+
require "ksuid/yaml"
124+
125+
class Example
126+
YAML.mapping id: KSUID
127+
end
128+
129+
example = Example.from_yaml(%(---\nid: aWgEPTl1tmebfsQzFP4bxwgy80V\n))
130+
# => #<Example:0x10a8723c0 @id=KSUID(aWgEPTl1tmebfsQzFP4bxwgy80V)>
131+
132+
example.to_yaml
133+
# => "---\nid: aWgEPTl1tmebfsQzFP4bxwgy80V\n"
134+
```
135+
120136
## Contributing
121137

122138
1. Fork it (<https://github.com/Sija/ksuid.cr/fork>)

spec/ksuid/yaml_spec.cr

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
require "../spec_helper"
2+
require "../../src/ksuid/yaml"
3+
4+
private class YAMLWithKSUID
5+
YAML.mapping value: KSUID
6+
end
7+
8+
describe KSUID do
9+
context "YAML mapping" do
10+
it "parses KSUID from YAML" do
11+
ksuid = YAMLWithKSUID.from_yaml(%(---\nvalue: 0o5Fs0EELR0fUjHjbCnEtdUwQe3\n))
12+
ksuid.should be_a(YAMLWithKSUID)
13+
ksuid.value.should eq(KSUID.from("0o5Fs0EELR0fUjHjbCnEtdUwQe3"))
14+
end
15+
end
16+
end

src/ksuid/yaml.cr

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
require "yaml"
2+
require "../ksuid"
3+
4+
# Adds YAML support to `KSUID` for use in a YAML mapping.
5+
#
6+
# NOTE: `require "ksuid/yaml"` is required to opt-in to this feature.
7+
#
8+
# ```
9+
# require "ksuid"
10+
# require "ksuid/yaml"
11+
#
12+
# class Example
13+
# YAML.mapping id: KSUID
14+
# end
15+
#
16+
# example = Example.from_yaml(%(---\nid: aWgEPTl1tmebfsQzFP4bxwgy80V\n))
17+
#
18+
# ksuid = KSUID.from("0o5Fs0EELR0fUjHjbCnEtdUwQe3")
19+
# ksuid.to_yaml # => "--- 0o5Fs0EELR0fUjHjbCnEtdUwQe3\n"
20+
# ```
21+
22+
struct KSUID
23+
def self.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node)
24+
unless node.is_a?(YAML::Nodes::Scalar)
25+
node.raise "Expected scalar, not #{node.class}"
26+
end
27+
from(node.value)
28+
end
29+
30+
def to_yaml(yaml : YAML::Nodes::Builder)
31+
yaml.scalar(to_s)
32+
end
33+
end

0 commit comments

Comments
 (0)