我有大量使用v0.9.3编写的系统,其中我通过重写serializable_object方法来劫持序列化过程:
在我的例子中,几乎每个调用都会序列化一些自定义多连接查询的结果,所以我们的序列化程序看起来像这样:
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在v0.10.x中实现类似覆盖的推荐方式(如果有)是什么?
发布于 2015-06-17 09:39:39
我认为最直接的方法是为您想要返回的每个值定义一个方法,并以每个值作为参数调用attributes。如下所示:
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
endhttps://stackoverflow.com/questions/30880317
复制相似问题