DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.04k stars 85 forks source link

Fix issue with serialization options not applied to nested objects #171

Closed osanay closed 3 months ago

osanay commented 3 months ago

In the current latest version 2.4.0, I noticed that serialization options are not applied to nested objects. For example, when specifying the serialize_enums_using_as_json option in the as_json method, it behaves as follows:

StoreModel.config.serialize_enums_using_as_json = false

class Message
  include StoreModel::Model

  attribute :child, to_type

  enum :status, in: { unread: 0, read: 1 }
end

message = Message.new(status: "read", child: { status: "unread" })
message.as_json(
  serialize_enums_using_as_json: true
) # => { "child" => { "child" => nil, "status" => 0 }, "status" => "read" }

The same issue occurs with the serialize_unknown_attributes option.

This problem seems to arise because the as_json method serializes nested objects recursively; however, the serialization options are not passed down to the nested objects.

I resolved this issue by storing the serialization options as attributes in the StoreModel::Model object. This ensures that the options are correctly inherited by nested objects during serialization.

I would appreciate your feedback on this solution.

osanay commented 3 months ago

LGTM! Do you think we need a major release for this change?

Thank you! This pull request addresses a bug related to nested objects. Since it fixes an existing issue and ensures the correct behavior, I believe a minor or patch release would be appropriate. However, there is also the change in the behavior of persisting unknown attributes in the database, so if there are new features or other changes planned for the near future, it might make sense to include this fix in a major release.