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

Loading dynamic field names during serialization #156

Open
rishijain opened this issue May 20, 2024 · 1 comment
Open

Loading dynamic field names during serialization #156

rishijain opened this issue May 20, 2024 · 1 comment

Comments

@rishijain
Copy link

Assume I have a model User, and it has a field custom1 and has other fields like id, name.
Now I have something like this:

class UserSerializer < Panko::Serializer
  attributes [:id, :name, :custom1]

end

And after serialization, the response looks like this:

[
   {
       id: 1,
       name: 'rishi'
       custom1: 'c1'
  },

   {
       id: 2,
       name: 'jain'
       custom1: 'c2'
  }
]

Now ideally I want to change the field name custom1 to something based on some logic. So it for first object, it can be "lookup-v1" and for second object in that response, it could be "lookup-v2".

Is there a way I can achieve this?

@rishijain rishijain changed the title loading dynamic fields during serialization loading dynamic field names during serialization May 20, 2024
@rishijain rishijain changed the title loading dynamic field names during serialization lLading dynamic field names during serialization May 20, 2024
@rishijain rishijain changed the title lLading dynamic field names during serialization Loading dynamic field names during serialization May 20, 2024
@yosiat
Copy link
Owner

yosiat commented Jun 13, 2024

Hey @rishijain

There is no way to achieve this in Panko, since the library is written upon assumption you will return the same-consistent structure. Adding support for this, will require big changes in the library that I wouldn't like to do.

I suggest wrapping the custom fields, under method attribute, like:

class UserSerializer < Panko::Serializer
  attributes :id, :name, :extras

  def extras
    out = {}
    if some_logic?
      out[:lookup-v1] = object.custom1
    else
      out[:lookup-v2] = object.custom1
    end
  end
end

Let me know if that answers your question.

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

No branches or pull requests

2 participants