Hi,
I’d like to suggest implementing the to_json method in dry-structs.
The basis of my argument is what would I expect as a novice user?
Here is an example:
class User < Dry::Struct
attribute :name, Types::String.optional
attribute :age, Types::Coercible::Integer
end
user = User.new({name: 'test', age: 3})
JSON.generate(user) # produces => "\"#<User:0x00005575205a1550>\""
This behavior was unexpected for me! In hindsight it is fairly obvious to me why it doesn’t work (because to_json isn’t implemented). And with a lot of tedious debugging I finally worked out what was going on (the default Object.to_json method is literally def to_json(*) to_s.to_json end.
However, learning all this took hours of time and a level of knowledge about JSON generation I’ve never needed before. I’ve been spoilt by rails where all the hard work has already been done!
I’ve gone ahead and derived my own struct base class which implements to_json, which I am now using:
class SerializableStruct < Dry::Struct
# Allows a struct to be serialized into JSON by first converting it to a hash
def to_json(*a)
to_h.to_json(*a)
end
end
May I suggest adding a default to_json method to dry-struct?
If not, a warning about a lack of default implementation of to_json in the documentation would go a long way to saving a lot of time for people like me.
