surrealist
surrealist copied to clipboard
Inherited Surrealist::Serializer does not accept array as object
I'm using Hanami as backend and I have this serializer here inheriting `Surrealist::Serializer)
When I tried to use a collection, it returns a weird result with the object stringifed.
module Serializers
class Impression < Surrealist::Serializer
json_schema do
{
id: Integer,
entity: String,
entity_id: Integer,
user_id: Integer
}
end
end
end
# returns an Array of Impressions
impressions = ImpressionRepository.new.all
Serializers::Impression.new(impressions).surrealize
# => "[\"#<Impression:0x00007f91aaa8cf80>\",\"#<Impression:0x00007f91aa27f400>\",\"#<Impression:0x00007f91aa27e3c0>\",\"#<Impression:0x00007f91aa27d380>\",\"#<Impression:0x00007f91aa27c340>\",\"#<Impression:0x00007f91aa2414c0>\",\"#<Impression:0x00007f91aa287768>\",\"#<Impression:0x00007f91aa286728>\",\"#<Impression:0x00007f91aa2856e8>\",\"#<Impression:0x00007f91aa2846a8>\",\"#<Impression:0x00007f91aa23a120>\",\"#<Impression:0x00007f91aa2381e0>\"]"
What works is mapping them into the serializer then using it as the object argument. I know this portion of docs is meant for AR but maybe I misread about accepting a collection?
https://github.com/nesaulov/surrealist#activerecord
Ok, looks like I may have misread it!
The constructor of Surrealist::Serializer takes two arguments: serializable model (or collection) and a context hash. So if there is an object that is not coupled to serializable model but it is still necessary for constructing JSON, you can pass it to constructor as a hash. It will be available in the serializer in the context hash.
I'm just wondering here, since using Surrealist::Serializer is to decouple the model from serializer, why can't we receive the collection raw, and use the base class itself to serialize the collection without needing to wrap them in a Serializable model?
We can use a raw object Serializers::Impression.new(Impression.new) but unable to use Serializers::Impression.new([Impression.new]).new
@choonggg try hash = Serializers::Impression.new([Impression.new]).build_schema
JSON.dump hash
Thanks @kolasss, it works. Just wondering if it can be done automatically or with another method without going through JSON/Oj dumping.
Hey @choonggg thank you for the issue, I will look into this during the week
great! @nesaulov thank you.