ActiveModel序列化继承

时间:2015-02-25 02:11:29

标签: ruby-on-rails active-model-serializers

说我有这个序列化器

    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之外的解决方案。

2 个答案:

答案 0 :(得分:9)

原来这个答案就是利用魔法include_xxx?方法...

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

这将使其仅序列化&#34; the_other&#34;

答案 1 :(得分:1)

BarSerializer设为父类,并将方法the_other放入其中。 FooSerializer将仅继承BarSerializer

中定义的方法和属性