Skip to content

Commit

Permalink
Fix Union.from_yaml to prioritize String for quoted scalar (#15405)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota authored Feb 5, 2025
1 parent 87faf5a commit 401443e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
12 changes: 12 additions & 0 deletions spec/std/yaml/serialization_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,18 @@ describe "YAML serialization" do
Bytes.from_yaml("!!binary aGVsbG8=").should eq("hello".to_slice)
end

describe "Union.from_yaml" do
it "String priorization" do
(Int32 | String).from_yaml(%(42)).should eq 42
(Int32 | String).from_yaml(%("42")).should eq "42"

(String | UInt32).from_yaml(%(42)).should eq 42
(String | UInt32).from_yaml(%("42")).should eq "42"

(Int32 | UInt32).from_yaml(%("42")).should eq 42
end
end

describe "parse exceptions" do
it "has correct location when raises in Nil#from_yaml" do
ex = expect_raises(YAML::ParseException) do
Expand Down
4 changes: 4 additions & 0 deletions src/yaml/enums.cr
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ module YAML
DOUBLE_QUOTED
LITERAL
FOLDED

def quoted?
single_quoted? || double_quoted?
end
end

enum SequenceStyle
Expand Down
7 changes: 7 additions & 0 deletions src/yaml/from_yaml.cr
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,13 @@ def Union.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node)
# So, we give a chance first to types in the union to be parsed.
{% string_type = T.find { |type| type == ::String } %}

{% if string_type %}
if node.as?(YAML::Nodes::Scalar).try(&.style.quoted?)
# do prefer String if it's a quoted scalar though
return String.new(ctx, node)
end
{% end %}

{% for type in T %}
{% unless type == string_type %}
begin
Expand Down

0 comments on commit 401443e

Please sign in to comment.