是的,您可以使用 :key 选项在序列化程序中自定义属性 name:
attribute :field_one__c, key: :field_one
attribute :field_two__c, key: :field_two
您还可以使用:if 或:unless 选项使任何属性有条件。
文档:https://github.com/rails-api/active_model_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