To send data to Google Analytics for e-commerce support, we needed to embed Order model data as a JSON object in the DOM. Because we needed to customize this JSON object and keep its logic separate from the Order model, we opted to use ActiveModel Serializers. We considered overriding the as_json method but didn't want to change the default to_json serialization behavior. ActiveModel Serializers allow us to build serializers for multiple use cases and keep them separate from the main Order model logic.
The required JSON object needed to include order data, line item data, and product data. The line item data would include all the attributes of Line Item. However, with the current implementation of
ActiveModel::Serializer, we needed to list all the attributes of Line Item as parameters to the
attributes class method.
class LineItemSerializer < ActiveModel::Serializer attributes :attr1, :attr2, :attr3, … # etc. There could be a lot of parameters here
Instead, it seemed...