Skip to content

Commit

Permalink
mapping: array field should return empty array rather than error when…
Browse files Browse the repository at this point in the history
… the field is missing
  • Loading branch information
maiha committed Aug 31, 2017
1 parent 6d73e62 commit 0a80110
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 1 deletion.
74 changes: 74 additions & 0 deletions spec/example/facebook_adcreatives_spec.cr
@@ -0,0 +1,74 @@
require "./spec_helper"

module Example::Facebook::AdCreatives
# account.adcreatives(fields: %w( title object_story_id object_story_spec ))
STR = <<-EOF
[
{
"title": "abc",
"object_story_spec": {
"page_id": "012345...",
"link_data": {
"link": "http://example.com/",
"message": "advertise message",
"name": "title",
"attachment_style": "link",
"image_hash": "c9e4c9...",
"call_to_action": {
"type": "LEARN_MORE"
},
"child_attachments": [
{
"link": "http://example.com/1",
"image_hash": "405bf...",
"name": "title of carousel1",
"call_to_action": {
"type": "LEARN_MORE"
}
},
{
"link": "http://example.com/2",
"image_hash": "9cef4...",
"name": "title of carousel2",
"call_to_action": {
"type": "LEARN_MORE"
}
}
]
}
}
}
]
EOF

class Attachment
Jq.mapping({
link: String,
name: String,
})
end

class LinkData
Jq.mapping({
link: String,
message: String,
name: String,
attachments: {Array(Attachment), ".child_attachments"},
})
end

class AdCreative
Jq.mapping({
title: String,
link_data: {LinkData, ".object_story_spec.link_data"},
})
end

describe "Example::Facebook::AdCreatives" do
it "works" do
creatives = Array(AdCreative).from_json(STR)
link = creatives[0].link_data
link.attachments.map(&.link).should eq(["http://example.com/1","http://example.com/2"])
end
end
end
38 changes: 38 additions & 0 deletions spec/example/facebook_adimages_spec.cr
@@ -0,0 +1,38 @@
require "./spec_helper"

module Example::Facebook::AdImages
# account.adimages(fields: ["name", "status", "creatives"])
STR = <<-EOF
[
{
"name": "abc",
"status": "ACTIVE",
"creatives": ["123456","789012"]
},
{
"name": "xyz",
"status": "ACTIVE"
}
]
EOF

class AdImage
Jq.mapping({
name: String,
status: String,
creatives: {Array(String), ".creatives"}
})
end

describe "Example::Facebook::AdImages" do
it "works with array field" do
images = Array(AdImage).from_json(STR)
images[0].creatives.should eq(["123456","789012"])
end

it "return empty array when array field is missing" do
images = Array(AdImage).from_json(STR)
images[1].creatives.should eq(Array(String).new)
end
end
end
6 changes: 5 additions & 1 deletion src/jq/mapping.cr
Expand Up @@ -34,7 +34,11 @@ class Jq

def {{key.id}}
if @{{key.id}}.nil?
default_{{key.id}}
{% if tuple[0].stringify =~ /^Array\(/ %}
{{tuple[0]}}.new
{% else %}
default_{{key.id}}
{% end %}
else
@{{key.id}}.not_nil!
end
Expand Down

0 comments on commit 0a80110

Please sign in to comment.