Jar*_*ish 5 ruby-on-rails active-model-serializers
我必须使用遗留应用程序,并且必须重写旧的(PHP基础)rest api.在旧的api中,当属性为null时,它变为空字符串.
然而,Rails只返回一个null,这会破坏应用程序.重写应用程序不是解决方案(即使这是最干净的方式).同样在旧的api中,其他值是(整数,布尔值,数字)的字符串.所以我想知道,如何在每个属性上执行to_s,而不是覆盖每个属性.我正在使用主动模型序列化器.
一点点元编程应该有所帮助:
class MySerializer < ActiveModel::Serializer
[:id, :attr1, :attr2, :attr2].each do |attr|
# Tell serializer its an attribute
attribute attr
# Define a method with the same name as the attribute that calls the
# underlying object and to_s on the result
define_method attr do
object.send(attr).to_s
end
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1910 次 |
| 最近记录: |