每当我呈现json或将其发布到某个队列时,我都想附加一个correlation_guid,这样我就可以在使用和推送数据的服务堆栈中跟踪它。
correlation_guid要么作为头部给出,要么不存在,在这种情况下,我会创建它。
这两个部分都很简单。最困难的部分实际上是把它粘在我的回复中。我在考虑修改方法to_json,这样无论何时调用该方法,它都会执行以下操作:
#should override other to_jsons
def to_json
unless self[:correlation_id]
self[:correlation_id] = header['CORRELATION-ID'] || SecureRandom.uuid
end
super
end 但是,我如何捕获所有的to_jsons?我知道数组,哈希,ActiveRecord,可能还有更多。此外,我非常确定上面的super不会起作用,但是我们的想法是使用原始对象的to_json。
发布于 2014-07-15 10:24:55
我认为您希望覆盖基础模型中的as_json。to_json调用as_json
# File activesupport/lib/active_support/core_ext/object/to_json.rb, line 15
def to_json(options = nil)
ActiveSupport::JSON.encode(self, options)
end
# File activesupport/lib/active_support/json/encoding.rb, line 48
def encode(value, use_options = true)
check_for_circular_references(value) do
jsonified = use_options ? value.as_json(options_for(value)) : value.as_json
jsonified.encode_json(self)
end
end这里还有一篇关于as_json和to_json之间区别的很好的文章:http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/
https://stackoverflow.com/questions/24748306
复制相似问题