Expected Behavior
A validation error (JSONAPI::Serializer::UnsupportedIncludeError) should be raised instead of breaking.
Actual Behavior
A NoMethodError is raised when trying to access .relationships_to_serialize, which is nil.
Steps to Reproduce the Problem
class S; include JSONAPI::Serializer; set_type :s; end
S.new({}, include: %i[invalid])
# => NoMethodError: undefined method `[]' for nil:NilClass from .../gems/jsonapi-serializer-2.2.0/lib/fast_jsonapi/object_serializer.rb:344:in `block in validate_includes!'
Specifications
- Version: 2.2.0
- Ruby version: 2.7.5
Discussion
Related, but possibly off-topic:
I also do a little bit of reflection on serializers, and the behavior of attributes_to_serialize and relationships_to_serialize - returning nil when empty - is kinda annoying. It's easy to workaround by appending .to_h to the returned values, but in this case I don't control how the gem itself handles it.
I saw that throughout the gem's code there are checks on these values. Wouldn't be easier to set default values on them instead? Likely here:
included do
class << self
attr_accessor :attributes_to_serialize,
:relationships_to_serialize #, ...
self.attributes_to_serialize = {}
self.relationships_to_serialize = {}
end
end
Or to use class_attribute, from active_support, which would handle inheritance and replace the manual handling?
included do
class_attribute :attributes_to_serialize, default: {}
class_attribute :relationships_to_serialize, default: {}
# ...
end
(It would require taking note of the caveat in class_attribute's documentation: when changing mutable objects, setters must be used instead of directly modifying the object.)
Expected Behavior
A validation error (
JSONAPI::Serializer::UnsupportedIncludeError) should be raised instead of breaking.Actual Behavior
A
NoMethodErroris raised when trying to access.relationships_to_serialize, which isnil.Steps to Reproduce the Problem
Specifications
Discussion
Related, but possibly off-topic:
I also do a little bit of reflection on serializers, and the behavior of
attributes_to_serializeandrelationships_to_serialize- returningnilwhen empty - is kinda annoying. It's easy to workaround by appending.to_hto the returned values, but in this case I don't control how the gem itself handles it.I saw that throughout the gem's code there are checks on these values. Wouldn't be easier to set default values on them instead? Likely here:
Or to use
class_attribute, fromactive_support, which would handle inheritance and replace the manual handling?(It would require taking note of the caveat in
class_attribute's documentation: when changing mutable objects, setters must be used instead of directly modifying the object.)