簡體   English   中英

ActiveModel序列化繼承

[英]ActiveModel serializer inheritance

說我有這個序列化器

    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

單個序列化值的操作有些昂貴...

然后我有另一個序列化器,它可以使用它,但不會返回所有成員:

    class BarSerializer < FooSerializr
      attributes :the_other
    end

這不起作用...... BarSerializer仍然會有這個,那個和另外的......

如何使用繼承但不能自動獲取相同的屬性? 我正在尋找除模塊mixins之外的解決方案。

原來這個答案就是利用魔法include_xxx? 方法...

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

這將使它只序列化“the_other”

BarSerializer設為父類,並將方法the_other放入其中。 FooSerializer將僅繼承BarSerializer定義的方法和屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM