【问题标题】:ActiveModel serializer inheritanceActiveModel 序列化程序继承
【发布时间】:2015-02-25 02:11:28
【问题描述】:

说我有这个序列化器

    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 仍然会拥有 this、that 和 the_other...

如何利用继承但不能自动获得相同的属性?我正在寻找模块 mixins 以外的解决方案。

【问题讨论】:

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


    【解决方案1】:

    原来这个问题的答案是利用魔法 include_xxx?方法...

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

    这将使它只序列化“the_other”

    【讨论】:

      【解决方案2】:

      BarSerializer 设为父类并将方法the_other 放入其中。 FooSerializer 将只继承BarSerializer 中定义的方法和属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 2010-12-15
        • 2019-11-17
        • 2014-10-21
        相关资源
        最近更新 更多