YAML Rubidium Deserialization

I work with DelayedJob and I need to override the method that I thought was used when the object is deserialized from YAML: self.yaml_new (defined in delayed/serialization/active_record )

My impression was that when YAML deserialized some data, it would call the yaml_new method on the data type class

DJ yaml_new method retrieves an object from the database using the passed in id

I cannot achieve this behavior with my own classes. When I set the self.yaml_new method in a class and try YAML.load on a serialized instance, it does not seem to call yaml_new , so I obviously should be wrong.

What is this method?

Searching yaml_new doesn't give much (just API documents from other people using it). Therefore, I wonder what exactly this method is.

I figured yaml_new is some kind of hook method that is called when an object of some type is detected, if that method exists in the class. But again, I can't get this to work. The following is an example:

 class B def self.yaml_new(klass, tag, val) puts "I'm in yaml new!" end end b = B.new YAML.load b.to_yaml # expected "I'm in yaml new!" got nothing 

Updates

So, after playing the game in my Rails application, it turned out that yaml_new indeed called from YAML.load . I have a file, for example:

 module ActiveRecord class Base def self.yaml_new(klass, tag, val) puts "\n\n yaml_new!!!\n\n" klass.find(val['attributes']['id']) rescue ActiveRecord::RecordNotFound raise Delayed::DeserializationError end def to_yaml_properties ['@attributes', '@database'] # add in database attribute for serialization end end end 

This is exactly what a DJ does, except that I record an action.

 YAML.load Contact.first.to_yaml # => yaml_new!!! 

I really get logged output !!

So what am I doing wrong outside my Rails application? Is there any other way to get this method to run? I ask because I try to check this in my own stone, and the yaml_new method yaml_new not start, so my tests fail, and yet it really works inside Rails

+4
source share
1 answer

You need to add something like

 yaml_as "tag:ruby.yaml.org,2002:B" 

before defining the self.yaml_new method. According to the comments in yaml / tag.rb, yaml_as:

Adds the taguri tag to the class used when dropping or loading the class in YAML. See YAML :: tag_class for details on input and taguris.

0
source

All Articles