Ruby yaml自定义域类型不保留类

cra*_*150 3 ruby yaml

我正在尝试使用自定义类型将持续时间对象(从ruby-duration gem)转储到yaml,因此它们在表单中表示hh:mm:ss.我试图修改这个问题的答案,但是在使用YAML.load解析yaml时,会返回Fixnum而不是Duration.有趣的是,Fixnum是持续时间中的总秒数,因此解析似乎有效,但在此之后转换为Fixnum.

我的代码到目前为止:

class Duration
  def to_yaml_type
    "!example.com,2012-06-28/duration"
  end

  def to_yaml(opts = {})
    YAML.quick_emit( nil, opts ) { |out|
      out.scalar( to_yaml_type, to_string_representation, :plain )
    }
  end

  def to_string_representation
    format("%h:%m:%s")
  end

  def Duration.from_string_representation(string_representation)
    split = string_representation.split(":")
    Duration.new(:hours => split[0], :minutes => split[1], :seconds => split[2])
  end
end

YAML::add_domain_type("example.com,2012-06-28", "duration") do |type, val|
  Duration.from_string_representation(val)
end
Run Code Online (Sandbox Code Playgroud)

澄清一下,我得到了什么结果:

irb> Duration.new(27500).to_yaml
=> "--- !example.com,2012-06-28/duration 7:38:20\n...\n"
irb> YAML.load(Duration.new(27500).to_yaml)
=> 27500
# should be <Duration:0xxxxxxx @seconds=20, @total=27500, @weeks=0, @days=0, @hours=7, @minutes=38>
Run Code Online (Sandbox Code Playgroud)

mat*_*att 6

看起来你正在使用较旧的Syck界面,而不是较新的Psych.而不是使用to_yamlYAML.quick_emit,你可以使用encode_with,而不是add_domain_type使用add_taginit_with.(这方面的文档很差,我能提供的最好的是链接到源代码).

class Duration
  def to_yaml_type
    "tag:example.com,2012-06-28/duration"
  end

  def encode_with coder
    coder.represent_scalar to_yaml_type, to_string_representation
  end

  def init_with coder
    split = coder.scalar.split ":"
    initialize(:hours => split[0], :minutes => split[1], :seconds => split[2])
  end

  def to_string_representation
    format("%h:%m:%s")
  end

  def Duration.from_string_representation(string_representation)
    split = string_representation.split(":")
    Duration.new(:hours => split[0], :minutes => split[1], :seconds => split[2])
  end
end

YAML.add_tag "tag:example.com,2012-06-28/duration", Duration

p s = YAML.dump(Duration.new(27500))
p YAML.load s
Run Code Online (Sandbox Code Playgroud)

这个输出是:

"--- !<tag:example.com,2012-06-28/duration> 7:38:20\n...\n"
#<Duration:0x00000100e0e0d8 @seconds=20, @total=27500, @weeks=0, @days=0, @hours=7, @minutes=38>
Run Code Online (Sandbox Code Playgroud)

(您看到的结果是持续时间中的总秒数,因为它被解析为六十进制整数.)