【问题标题】:Ruby on Rails - Does attribute order matter in an ActiveModel:Serializer?Ruby on Rails - ActiveModel:Serializer 中的属性顺序是否重要?
【发布时间】:2019-04-12 12:47:55
【问题描述】:

我有一个简单的序列化器,其中一个属性的处理取决于另一个属性的处理。

所以我的代码看起来像:

class CounterSerializer < ActiveModel::Serializer

  attribute :CounterId do
    object.id
  end

  attribute :CounterValue do
    @value = SomeClass.get_counter_value(object.id)
  end

  attribute :NextCounterValue do
    @value + 1
  end
end 

所以,假设我在两个属性中使用了@value,并且第二个属性的值取决于第一个属性的输出,我可以假设CounterValue 将被计算之前 @987654324 @? (即没有异步计算问题)

还请记住,NextCounterValue 不应再次调用 SomeClass.get_counter_value(性能问题)

【问题讨论】:

  • 我猜是的。通常属性按序列化程序文件中指定的顺序显示。因此,计算也将按照提到的顺序一一进行。

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


【解决方案1】:

我猜你的代码应该工作,但如果你想确保你的代码能工作,我建议你使用memoization

class CounterSerializer < ActiveModel::Serializer

  attributes :counterId, :counterValue, :nextCounterValue

  def counterId
    object.id
  end

  def counterValue
    @value ||= SomeClass.get_counter_value(object.id)
  end

  def nextCounterValue
    counterValue + 1
  end
end

感谢 memoization,此代码不会再次调用 SomeClass.get_counter_value,您将确保您的代码行为符合您的要求。

【讨论】:

    猜你喜欢
    • 2017-08-09
    • 2020-02-13
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2013-01-08
    • 1970-01-01
    • 2014-04-14
    相关资源
    最近更新 更多