Reputation: 2061
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
...?
Upvotes: 2
Views: 2678
Reputation: 106027
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
Upvotes: 1