每当我渲染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
?我知道Array,Hash,ActiveRecord,可能还有更多。此外,我非常确定super
如上所述不会起作用,但我们的想法是使用原始对象的to_json
。
答案 0 :(得分:0)
我认为您希望覆盖基础模型中的as_json
。 as_json
调用to_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/