From 75f7dd25220b6899633465dbd579f7e41370026b Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Wed, 22 May 2019 09:51:33 -0300 Subject: [PATCH] YAML: let String handle numbers too --- spec/std/yaml/mapping_spec.cr | 14 ++++++++++++++ spec/std/yaml/serialization_spec.cr | 6 ++---- src/yaml/from_yaml.cr | 12 +++++++++++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/spec/std/yaml/mapping_spec.cr b/spec/std/yaml/mapping_spec.cr index 55c5faba9fe8..6330dec4dbf8 100644 --- a/spec/std/yaml/mapping_spec.cr +++ b/spec/std/yaml/mapping_spec.cr @@ -103,6 +103,12 @@ private class YAMLWithPresence }) end +private class YAMLWithString + YAML.mapping({ + value: String, + }) +end + class YAMLRecursive YAML.mapping({ name: String, @@ -530,4 +536,12 @@ describe "YAML mapping" do it "calls #finalize" do assert_finalizes(:yaml) { YAMLWithFinalize.from_yaml("---\nvalue: 1\n") } end + + it "parses string even if it looks like a number" do + yaml = YAMLWithString.from_yaml <<-YAML + --- + value: 12.34 + YAML + yaml.value.should eq("12.34") + end end diff --git a/spec/std/yaml/serialization_spec.cr b/spec/std/yaml/serialization_spec.cr index 96d7b5bbf05e..6687c0099116 100644 --- a/spec/std/yaml/serialization_spec.cr +++ b/spec/std/yaml/serialization_spec.cr @@ -55,10 +55,8 @@ describe "YAML serialization" do String.from_yaml("hello").should eq("hello") end - it "raises on reserved string" do - expect_raises(YAML::ParseException) do - String.from_yaml(%(1.2)) - end + it "can parse string that looks like a number" do + String.from_yaml(%(1.2)).should eq ("1.2") end it "does Float32#from_yaml" do diff --git a/src/yaml/from_yaml.cr b/src/yaml/from_yaml.cr index 36298f01fd73..faf763894a66 100644 --- a/src/yaml/from_yaml.cr +++ b/src/yaml/from_yaml.cr @@ -53,7 +53,17 @@ end {% end %} def String.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) - parse_scalar(ctx, node, self) + ctx.read_alias(node, String) do |obj| + return obj + end + + if node.is_a?(YAML::Nodes::Scalar) + value = node.value + ctx.record_anchor(node, value) + value + else + node.raise "Expected String, not #{node.class.name}" + end end def Float32.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node)