Skip to content

Commit 28484f8

Browse files
samueleatonRX14
authored andcommittedSep 13, 2017
adds nilable casting for greater parity with JSON::Any (#4963)
1 parent 5eb5490 commit 28484f8

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed
 

‎spec/std/yaml/any_spec.cr

+6
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,20 @@ describe YAML::Any do
99

1010
it "gets string" do
1111
YAML.parse("hello").as_s.should eq("hello")
12+
YAML.parse("hello").as_s?.should eq("hello")
13+
YAML.parse("hello:\n- cruel\n- world\n").as_s?.should be_nil
1214
end
1315

1416
it "gets array" do
1517
YAML.parse("- foo\n- bar\n").as_a.should eq(["foo", "bar"])
18+
YAML.parse("- foo\n- bar\n").as_a?.should eq(["foo", "bar"])
19+
YAML.parse("hello").as_a?.should be_nil
1620
end
1721

1822
it "gets hash" do
1923
YAML.parse("foo: bar").as_h.should eq({"foo" => "bar"})
24+
YAML.parse("foo: bar").as_h?.should eq({"foo" => "bar"})
25+
YAML.parse("foo: bar")["foo"].as_h?.should be_nil
2026
end
2127
end
2228

‎src/yaml/any.cr

+18
Original file line numberDiff line numberDiff line change
@@ -157,18 +157,36 @@ struct YAML::Any
157157
@raw.as(String)
158158
end
159159

160+
# Checks that the underlying value is `String`, and returns its value.
161+
# Returns `nil` otherwise.
162+
def as_s? : String?
163+
as_s if @raw.is_a?(String)
164+
end
165+
160166
# Checks that the underlying value is `Array`, and returns its value.
161167
# Raises otherwise.
162168
def as_a : Array(Type)
163169
@raw.as(Array)
164170
end
165171

172+
# Checks that the underlying value is `Array`, and returns its value.
173+
# Returns `nil` otherwise.
174+
def as_a? : Array(Type)?
175+
as_a if @raw.is_a?(Array(Type))
176+
end
177+
166178
# Checks that the underlying value is `Hash`, and returns its value.
167179
# Raises otherwise.
168180
def as_h : Hash(Type, Type)
169181
@raw.as(Hash)
170182
end
171183

184+
# Checks that the underlying value is `Hash`, and returns its value.
185+
# Returns `nil` otherwise.
186+
def as_h? : Hash(Type, Type)?
187+
as_h if @raw.is_a?(Hash(Type, Type))
188+
end
189+
172190
# :nodoc:
173191
def inspect(io)
174192
@raw.inspect(io)

0 commit comments

Comments
 (0)
Please sign in to comment.