Skip to content

Commit

Permalink
Merge pull request #7809 from asterite/feature/yaml-string
Browse files Browse the repository at this point in the history
YAML: let String handle numbers too
  • Loading branch information
asterite authored May 22, 2019
2 parents b038213 + 75f7dd2 commit 349b0a1
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
14 changes: 14 additions & 0 deletions spec/std/yaml/mapping_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ private class YAMLWithPresence
})
end

private class YAMLWithString
YAML.mapping({
value: String,
})
end

class YAMLRecursive
YAML.mapping({
name: String,
Expand Down Expand Up @@ -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
6 changes: 2 additions & 4 deletions spec/std/yaml/serialization_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 11 additions & 1 deletion src/yaml/from_yaml.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 349b0a1

Please sign in to comment.