简体   繁体   English

ActiveModel序列化继承

[英]ActiveModel serializer inheritance

say I have this serializer 说我有这个序列化器

    class FooSerializer < ActiveModel::Serializer
      attributes :this, :that, :the_other

      def this
        SomeThing.expensive(this)
      end

      def that
        SomeThing.expensive(that)
      end

      def the_other
        SomeThing.expensive(the_other)
      end
    end

Where the operations for the individual serialized values is somewhat expensive... 单个序列化值的操作有些昂贵...

And then I have another serializer that whats to make use of that, but not return all of the members: 然后我有另一个序列化器,它可以使用它,但不会返回所有成员:

    class BarSerializer < FooSerializr
      attributes :the_other
    end

This does not work... BarSerializer will still have this, that, and the_other... 这不起作用...... BarSerializer仍然会有这个,那个和另外的......

How can I make use of inheritance but not automatically get the same attributes? 如何使用继承但不能自动获取相同的属性? I am looking for a solution other than module mixins. 我正在寻找除模块mixins之外的解决方案。

Turns out the answer to this is to make use of the magic include_xxx? 原来这个答案就是利用魔法include_xxx? methods... 方法...

class BarSerializer < FooSerializr
  def include_this?; false; end
  def include_that?; false; end
end

This will make it only serialize "the_other" 这将使它只序列化“the_other”

Make the BarSerializer the parents class and put the method the_other in it. BarSerializer设为父类,并将方法the_other放入其中。 FooSerializer will inherits only the method and the attribute defined in BarSerializer . FooSerializer将仅继承BarSerializer定义的方法和属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM