Skip to content

Commit

Permalink
Provide defaults when underlying data is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
gburgett committed Nov 26, 2024
1 parent dfc697f commit f2f193b
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
2 changes: 1 addition & 1 deletion wcc-contentful/lib/wcc/contentful/metadata.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Struct.new(:raw) do
def tags
@tags ||=
Array(raw['tags']).map do |tag|
Array(raw['tags'] || []).map do |tag|
WCC::Contentful::Link.new(tag) if tag.is_a?(Hash)
end
end
Expand Down
2 changes: 1 addition & 1 deletion wcc-contentful/lib/wcc/contentful/model_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def build_model(typedef)
)

@metadata = WCC::Contentful::Metadata.new(
raw['metadata']
raw['metadata'] || {}
)

typedef.fields.each_value do |f|
Expand Down
64 changes: 64 additions & 0 deletions wcc-contentful/spec/wcc/contentful/model_builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,70 @@ class MyButton < WCC::Contentful::Model::MenuButton
expect(entry.metadata.tags.first).to be_a(WCC::Contentful::Link)
expect(entry.metadata.tags.first.id).to eq('ministry-regeneration')
end

it 'metadata is nil when not present' do
@schema = subject.build_models

entry_without_metadata = JSON.parse <<~JSON
{
"fields": {
"title": "Hello, World!"
},
"sys": {
"id": "5KsDBWseXY6QegucYAoacS",
"type": "Entry",
"contentType": {
"sys": {
"type": "Link",
"linkType": "ContentType",
"id": "page"
}
},
"createdAt": "2016-12-20T10:43:35.772Z",
"updatedAt": "2016-12-20T10:43:35.772Z",
"revision": 1,
"locale": "en-US"
}
}
JSON

entry = WCC::Contentful::Model.new_from_raw(entry_without_metadata)
expect(entry.metadata).to_not be_nil
expect(entry.metadata.tags).to eq([])
end

it 'tags are empty when not present' do
@schema = subject.build_models

entry_without_metadata = JSON.parse <<~JSON
{
"fields": {
"title": "Hello, World!"
},
"metadata": {
},
"sys": {
"id": "5KsDBWseXY6QegucYAoacS",
"type": "Entry",
"contentType": {
"sys": {
"type": "Link",
"linkType": "ContentType",
"id": "page"
}
},
"createdAt": "2016-12-20T10:43:35.772Z",
"updatedAt": "2016-12-20T10:43:35.772Z",
"revision": 1,
"locale": "en-US"
}
}
JSON

entry = WCC::Contentful::Model.new_from_raw(entry_without_metadata)
expect(entry.metadata).to_not be_nil
expect(entry.metadata.tags).to eq([])
end
end

def with_tempfile(name, contents)
Expand Down

0 comments on commit f2f193b

Please sign in to comment.