active_model_serializers
active_model_serializers copied to clipboard
Overriding object name
Expected behavior vs actual behavior
So, we want to have the key object to be present in the response of the serializer. However, since object is defined as attr_accessor :object.
https://github.com/QultureRocks/active_model_serializers/blob/306eab0953cf74fa9a87da7f43687e1ce6a3ce0a/lib/active_model/serializer.rb#L314
It's hard to override, since we want to include the object key in the response. Is there any way to redefine the object as another serializer attribute, something like record?.
We can provide an option to override the key name, which then defaults to object?.
We can change the constructor to accept another argument, namely the object_name?.
https://github.com/QultureRocks/active_model_serializers/blob/306eab0953cf74fa9a87da7f43687e1ce6a3ce0a/lib/active_model/serializer.rb#L319-L329
This then can be done as follows
def initialize(object, options = {})
if options[:object_name]
self.class.instance_eval do
attr_accessor options[:object_name]
end
end
end
What do you guys think?