yosiat / panko_serializer

High Performance JSON Serialization for ActiveRecord & Ruby Objects
https://panko.dev
MIT License
592 stars 36 forks source link

Loading dynamic field names during serialization #156

Open rishijain opened 6 months ago

rishijain commented 6 months ago

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?

yosiat commented 5 months ago

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.