codenoble / cache-crispies

Speedy Rails JSON serialization with built-in caching
MIT License
156 stars 14 forks source link

Don't try to serialize nested attributes that are nil #21

Closed floriandejonckheere closed 4 years ago

floriandejonckheere commented 4 years ago

When serializing a nested object that happens to be nil, don't try to naively serialize it (which results in a NoMethodError being thrown, but render a nil instead.

class ChildSerializer < CacheCrispies::Base
  serialize :field
end

class ParentSerializer < CacheCrispies::Base
  # Optional field
  serialize :child, with: ChildSerializer
end

my_child = OpenStruct.new(field: "My field")

parent = OpenStruct.new(child: my_child)
childless_parent = OpenStruct.new(child: nil)

ParentSerializer.new(parent).as_json
#=> {:child=>{:field=>"My field"}}

ParentSerializer.new(childless_parent).as_json
#=> {:child=>nil}
codeclimate[bot] commented 4 years ago

Code Climate has analyzed commit 2877131b and detected 0 issues on this pull request.

The test coverage on the diff in this pull request is 100.0% (95% is the threshold).

This pull request will bring the total coverage in the repository to 100.0% (0.0% change).

View more on Code Climate.

adamcrown commented 4 years ago

Thanks @floriandejonckheere. This seems very reasonable, and thanks for adding tests. I'll treat this as a bug and release a 1.1.2 here soon.