ruby 有没有一种方法可以在不丢失任何信息的情况下序列化和重复化法拉第::响应?

kxe2p93d  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(76)

我正在尝试序列化Faraday::Response示例而不丢失任何信息。我找到了marshal_dumpmarshal_load方法,但它们似乎没有保留response.env.request的细节。

response = Faraday.get('https://google.com')
response.env.request_headers
#=> {"User-Agent"=>"Faraday v2.7.4"}

response2 = Faraday::Response.new
response2.marshal_load(response.marshal_dump)
response2.env.request_headers
#=> nil

response3 = Marshal.load(Marshal.dump(response))
response3.env.request_headers
#=> nil

我怎样才能序列化所有东西,以便在序列化时,两个对象包含完全相同的数据?

laawzig2

laawzig21#

不会丢失任何信息
一般来说,这是不可能的。例如,请求有@on_complete_callbacks,它们是proc,并且不能被编组。在顶部-对象可以引用其他对象,并且在某些情况下(例如,匿名类),这些也不能被编组。
法拉第的marshal_dump就是这个

def marshal_dump
  finished? ? to_hash : nil
end

(来源:https://www.rubydoc.info/github/lostisland/faraday/Faraday/Response#marshal_dump-instance_method)
to_hash是:

def to_hash
  {
    status: env.status, body: env.body,
    response_headers: env.response_headers,
    url: env.url
  }
end

(来源:https://www.rubydoc.info/github/lostisland/faraday/Faraday/Response#to_hash-instance_method)
所以,正如你所看到的--法拉第的开发者们做出了一个决定,其他的一切都不那么重要。
因此,快捷方式“只是以一种在序列化后完全相同的方式序列化”是不可能的,所以你需要:

  • 实现自己的对象(例如, Package 器),您可以在其中实现自己的序列化,但您必须决定哪些数据是重要的
  • 或者,重新定义你原来要解决的问题,并尝试寻找其他可能的解决方案(你没有分享为什么你需要它,所以很难帮助你)。

相关问题