[英]How to define method serializer in Rails netflix fast_jsonapi in Rails?
如何在 Rails 中使用 Rails Netflix fast_jsonapi 在 Serializer 中定義函數,就像活動模型序列化器一樣?
來自 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
它很難。 這在不久前被提出作為一個問題,但還沒有任何結果。
發生的事情是序列化程序有點像單例,所以你基本上被迫使用類方法,例如
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 中的范圍界定有一些奇怪的東西,這使得這很有必要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.