Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overriding object name #2437

Open
rockwellll opened this issue Jul 21, 2022 · 0 comments
Open

Overriding object name #2437

rockwellll opened this issue Jul 21, 2022 · 0 comments

Comments

@rockwellll
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant