문제

I'm trying to understand the serialization/deserialization of ruby object using YAML under 1.8.7 and 1.9+ and have a few queries regarding it (I can't find much documentation on this)

Ruby 1.8.7

class Element
    yaml_as "tag:ruby.yaml.org,2002:Element"

    def self.yaml_new(klass, tag, val)
      puts "print you are in yaml"
    end
  end


  YAML.parser
  => syck     ## parser is set as syck all good     
   e =  Element.new.to_yaml
   => "--- !ruby/Element {}\n\n" 

Question 1: Now why didn't I get tag:ruby.yaml.org,2002:Element instead of --- !ruby/Element {}\n\n ?

  YAML.load(e) 
  =>  print your are in "yaml" ##print statement execute all good 

  ## Not sure who to change the parser in 1.8 to `pysch` so skipping this part

Ruby 1.9+

  YAML::ENGINE.yamler
   => pysch 
   e =  Element.new.to_yaml  
   => "--- !<tag:ruby.yaml.org,2002:Element> {}\n"  ## I see the tag in 1.9+ fine 

Question 2 : Why is it working in 1.9+ and not in 1.8.7 ?

   YAML.load(e)
   =>    ## The print is not getting printed 

Question 3: Why print you are in yaml isn't getting printed? In other words, why is self.yaml_new not getting invoked on YAML.load? Is it not supported under 1.9+ ?

   YAML::ENGINE.yamler = 'syck'
   => syck
   u =  Element.new.to_yaml
   => "--- !ruby/object:Element {}\n\n" 

Question 4 (similar to question #1) : Why is the the tag(tag:ruby.yaml.org,2002:Element) missing in the serialize yaml above

   YAML.load(e)
   =>  ## Suprisingly, print is not executed 

Question 5 (similar to question #2): Why isn't self.yaml_new getting executed for syck and pysch parser in ruby 1.9+ ?

Can anyone can help me resolve these questions?

도움이 되었습니까?

해결책

  • Question 1: I don't have any answer for this one
  • Question 2: Because Psych handles it correctly but you should use yaml_tag instead of yaml_tag
  • Question 3: Use def yaml_initialize(tag, val) and it will work
  • Question 4: Because it's Syck again, it behaves like in Ruby 1.8
  • Question 5: Same as Q4
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top