开发者

Serialize Mail::Message to yaml like other objects

开发者 https://www.devze.com 2023-03-04 16:18 出处:网络
Problem Normal objects serialize to something like: \"--- !ruby/object {}\\n\\n\" whereas Mail::Message serialize to:

Problem

Normal objects serialize to something like:

"--- !ruby/object {}\n\n"

whereas Mail::Message serialize to:

"--- \nMime-Version: \"1.0\"\nbody: \"\"\nContent-Transfer-Encoding:[…]"

Question

How can I have Mail::Message serialized just like other objects?

Background

Gem Versions:

  • YAML: "0.60"
  • Mail: "2.2.19"

Code

Object.new.to_yaml #gives
"--- !ruby/object {}\n\n"

Mail::Message.new.to_y开发者_JAVA技巧aml #gives
"--- \nMime-Version: \"1.0\"\nbody: \"\"\nContent-Transfer-Encoding: 7bit\nMessage-ID: <4dc418052be4a_16b62850c31ac91488@mbp.local.mail>\nsubject: \nContent-Type: text/plain\nDate: Fri, 06 May 2011 15:47:17 +0000\n"

Desired output

"--- !ruby/object:Mail::Message {}\n\n"


The reason was a flawed patch to the Mail gem. Details are outlined here:

https://github.com/mikel/mail/pull/237


Since Mail::Message has the own to_yaml method - https://github.com/mikel/mail/blob/master/lib/mail/message.rb#L1714 - I think it's impossible without monkey-patching like

module Mail
  class Message
    def to_yaml
      self.class.name.to_yaml
    end
  end
end

irb(main):011:0> Mail::Message.new.to_yaml
=> "--- Mail::Message\n...\n"


Use YAML directly instead of going through to_yaml method.

YAML.dump(Mail::Message.new)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号