我的rest有一个序列化程序。目前看来:
class TestSerializer < ActiveModel::Serializer
attributes :id, :name, :field_one__c, :field_two__c
end
我想知道是否有任何方法来过滤所有字段,以便在序列化时删除__c
,以及是否有一种方法将逻辑应用于所有字段。
在这种情况下,我在最后有很多带有__c
的字段,我想用序列化程序级别上最少的代码来删除它们。
发布于 2017-09-15 04:52:56
是的,您可以使用选项自定义序列化程序中的属性:
attribute :field_one__c, key: :field_one
attribute :field_two__c, key: :field_two
您还可以使用或:unless
选项将任何属性设置为条件。
医生:serializers/blob/v0.10.6/docs/general/serializers.md#attribute
更新:
对于特殊情况,您可以通过在属性列表之前定义attributes
类方法来破解这个问题:
class TestSerializer < ActiveModel::Serializer
class << self
def attributes(*attrs)
attrs.each do |attr|
options = {}
options[:key] = attr.to_s[0..-4].to_sym if attr.to_s.end_with?('__c')
attribute(attr, options)
end
end
end
attributes :id, :name, :field_one__c, :field_two__c
end
如果您有多个序列化类,并且需要过滤大量属性,则可以通过创建将从ActiveModel::Serializer
继承的另一个序列化程序类,在解决方案中应用DRY原则。将上述类方法定义放在这个新的序列化程序中,并从这个带有__c
属性列表的新序列化器继承所有序列化程序。
class KeyFilterSerializer < ActiveModel::Serializer
class << self
def attributes(*attrs)
attrs.each do |attr|
options = {}
options[:key] = attr.to_s[0..-4].to_sym if attr.to_s.end_with?('__c')
attribute(attr, options)
end
end
end
end
class TestSerializer < KeyFilterSerializer
attributes :id, :name, :field_one__c, :field_two__c
end
class AnotherTestSerializer < KeyFilterSerializer
attributes :id, :name, :field_one__c, :field_two__c
end
https://stackoverflow.com/questions/46227382
复制