代码之家  ›  专栏  ›  技术社区  ›  alavni shubham

如何在rails中定义方法序列化程序netflix fast\u jsonapi在rails中?

  •  0
  • alavni shubham  · 技术社区  · 7 年前

    如何使用Rails中的Rails Netflix fast\u jsonapi在序列化程序中定义函数,就像活动模型序列化程序一样?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Denny Mueller    7 年前

    来自fastèjsonapi的自述

    class MovieSerializer
      include FastJsonapi::ObjectSerializer
    
      attributes :name, :year
    
      attribute :name_with_year do |object|
        "#{object.name} (#{object.year})"
      end
    end
    

    class MovieSerializer
      include FastJsonapi::ObjectSerializer
    
      attributes :name, :year
    
      attribute :name_with_year do |object|
        foo(object)
      end
    
      def foo(object)
        # do something with object
      end
    end
    
        2
  •  0
  •   Glyoko    7 年前

    这是。。。困难。这是作为一个 issue 有段时间了,但还没有结果。

    所发生的事情是,序列化程序的行为有点像单例,所以您基本上被迫使用类方法,例如

    class MovieSerializer
      include FastJsonapi::ObjectSerializer
    
      attributes :name, :year
    
      attribute :name_with_year do |object|
        foo(object)
      end
    
      def self.foo(object) # will be called
        # do something with object
      end
    
      def foo(object) # will never be called
        # do something with object
      end
    end
    

    在宝石中有一些奇怪的东西使得这很有必要。