wmakley / tiny_serializer

Simple Ruby JSON Serialization DSL. Replaces active_model_serializers.
MIT License
53 stars 2 forks source link

Support for polymorphic associations #11

Open CEB-21 opened 5 years ago

CEB-21 commented 5 years ago

Currently if a polymorphic association is added to a serializer for instance:

class BoardSerializer < TinySerializer
  attribute :id

  belongs_to :boardable
end

and the serializer is instantiated as so:

BoardSerializer.new(obj).serialize

An error is raised

NameError (uninitialized constant BoardableSerializer)

It would be great if support for these type of associations was added in a future release. Unless I've overlooked how to accomplish this.

wmakley commented 5 years ago

As you noticed, the code infers a serializer class from the property name. The way serializers are configured would need to be significantly refactored to allow for a dynamic sub-record serializer. I didn't implement it that way because I wanted it to be entirely prescriptive and to have no "magic". (In my usage, I almost always specify the serializer class.) One of my goals was to crash early and often if I was missing a serializer.

I do not have time to work on this right now due to many transitions in my life, but I would accept a PR to modify dsl.rb to allow #sub_records to specify the serializer as a Proc or :polymorphic (+ additional code to infer the serializer at runtime) or whatever seems simplest to you. KISS.