Sitelet https://github.com/jsonapi-serializer/jsonapi-serializer/issues/210
Skip to content

A serializer without relationships breaks when passing include option to .new #210

Description

@13k

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.)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions