yosiat / panko_serializer

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

Delegate + aliases not working as expected #102

Open danielnc opened 3 years ago

danielnc commented 3 years ago

I have a AR model that has a db column called state, and I want to transform it before serializing the data. That method that transforms data lives on the AR model

When delegating the method to the AR object + aliasing it, panko is not working the way I would expect. it's returning the actual persisted database value for object#state

class StateSerializer  < Panko::Serializer
  attributes :state

  aliases friendly_state: :state
  delegate :friendly_state, to: :object
end
class ActivityLog < ApplicationRecord
   def friendly_state
    case state
    when "error"
      "User Error"
    else
      state
    end
  end
end

I can accomplish what I want by doing but I think it would be a better approach to be able to rely on aliases + method delegation

class StateSerializer  < Panko::Serializer
  attributes :state

  def state
    object.friendly_state
  end
end
yosiat commented 3 years ago

@danielnc Thanks for reporting this issue!

I see what you say and totally agree, this happens because aliases works on attributes and not on methods. Since serializer is not strict to specific model (as of today), I can't know if "friendly_state" is a method on a model and then alias to it's method.

Making serializers strongly typed, is something I want to achieve in the future but not now.

I'll try to think about an options how to solve this without complicating the library.

If you want to submit PR and need help with it, I'll be gladly guide you (you can join the Slack group)