如何在 Rails netflix fast_jsonapi 中定义方法序列化程序 Rails?
How to define method serializer in Rails netflix fast_jsonapi in Rails?
如何使用 Rails Netflix fast_jsonapi 在 Rails 中像活动模型序列化程序一样在序列化程序中定义函数?
来自 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
这……很难。前一阵子 issue 提出了这个问题,但目前还没有结果。
发生的事情是序列化器有点像单例,所以你基本上被迫使用 class 方法,例如
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
gem 范围界定有一些奇怪的东西,因此有必要这样做。
如何使用 Rails Netflix fast_jsonapi 在 Rails 中像活动模型序列化程序一样在序列化程序中定义函数?
来自 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
这……很难。前一阵子 issue 提出了这个问题,但目前还没有结果。
发生的事情是序列化器有点像单例,所以你基本上被迫使用 class 方法,例如
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
gem 范围界定有一些奇怪的东西,因此有必要这样做。