Skip to content

Commit

Permalink
adds nilable casting for greater parity with JSON::Any (#4963)
Browse files Browse the repository at this point in the history
  • Loading branch information
samueleaton authored and RX14 committed Sep 13, 2017
1 parent 5eb5490 commit 28484f8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spec/std/yaml/any_spec.cr
Expand Up @@ -9,14 +9,20 @@ describe YAML::Any do

it "gets string" do
YAML.parse("hello").as_s.should eq("hello")
YAML.parse("hello").as_s?.should eq("hello")
YAML.parse("hello:\n- cruel\n- world\n").as_s?.should be_nil
end

it "gets array" do
YAML.parse("- foo\n- bar\n").as_a.should eq(["foo", "bar"])
YAML.parse("- foo\n- bar\n").as_a?.should eq(["foo", "bar"])
YAML.parse("hello").as_a?.should be_nil
end

it "gets hash" do
YAML.parse("foo: bar").as_h.should eq({"foo" => "bar"})
YAML.parse("foo: bar").as_h?.should eq({"foo" => "bar"})
YAML.parse("foo: bar")["foo"].as_h?.should be_nil
end
end

Expand Down
18 changes: 18 additions & 0 deletions src/yaml/any.cr
Expand Up @@ -157,18 +157,36 @@ struct YAML::Any
@raw.as(String)
end

# Checks that the underlying value is `String`, and returns its value.
# Returns `nil` otherwise.
def as_s? : String?
as_s if @raw.is_a?(String)
end

# Checks that the underlying value is `Array`, and returns its value.
# Raises otherwise.
def as_a : Array(Type)
@raw.as(Array)
end

# Checks that the underlying value is `Array`, and returns its value.
# Returns `nil` otherwise.
def as_a? : Array(Type)?
as_a if @raw.is_a?(Array(Type))
end

# Checks that the underlying value is `Hash`, and returns its value.
# Raises otherwise.
def as_h : Hash(Type, Type)
@raw.as(Hash)
end

# Checks that the underlying value is `Hash`, and returns its value.
# Returns `nil` otherwise.
def as_h? : Hash(Type, Type)?
as_h if @raw.is_a?(Hash(Type, Type))
end

# :nodoc:
def inspect(io)
@raw.inspect(io)
Expand Down

0 comments on commit 28484f8

Please sign in to comment.