how can i write a custom serialization method in active-model-serializers v0.10.x...?

2.5k views Asked by At

i have substantial system written using v0.9.3 where i hijack the serialization process by overriding the serializable_object method:

in my case, pretty much every call ends up serializing the result of some custom multi-join query, so our serializers look something like this:

class DatesSerializer < ActiveModel::Serializer
  include DateUtils

  def serializable_object(opts={})
    max = object[:max]
    min = object[:min]
    if max.blank?
      max = current_month
      min = max
    end

    {
      minMonth: min.to_s,
      maxMonth: max.to_s,
      startMonth: [min, relative_month(yyyymm: max, distance: -11)].max.to_s,
      endMonth: max.to_s
    }
  end
end

what would be the recommended way (if any) to accomplish similar override in v0.10.x...?

1

There are 1 answers

1
Jordan Running On

I think the most straightforward way is to define a method for each value you want to return and call attributes with each one as an argument. Something like this:

class DatesSerializer < ActiveModel::Serializer
  include DateUtils

  attributes :minMonth, :maxMonth, :startMonth, :endMonth

  def minMonth
    min.to_s
  end

  def maxMonth
    max.to_s
  end

  def startMonth
    [ min,
      relative_month(yyyymm: max, distance: -11)
    ].max.to_s
  end

  def endMonth
    maxMonth
  end

  private
  def min
    return min if object[:max].present?
    object[:max]
  end

  def max
    return object[:max] if object[:max].present?
    current_month
  end
end