title: Ruby deserializing YAML
body: <p>I'm working with DelayedJob and I need to override a method that I <em>thought</em> was being used when an object is deserialized from YAML: <code>self.yaml_new</code> (defined in in <code>delayed/serialization/active_record</code>)</p>
  
  <p>My impression was that when YAML deserialized some data, it would call the <code>yaml_new</code> method on the class of the type of that data</p>
  
  <p>DJ's <code>yaml_new</code> method fetches the object from the database using the passed in id</p>
  
  <p>I'm unable to achieve this behaviour with my own classes.  When I set a <code>self.yaml_new</code> method on a class and try to <code>YAML.load</code> on a serialized instance, it doesn't seem to call <code>yaml_new</code> so I must obviously be mistaken.</p>
  
  <p>What then is this method for?</p>
  
  <p>Searching for <code>yaml_new</code> doesn't yield much (just API docs of other people using it).  So I'm wondering what exactly this method is.  </p>
  
  <p>I figured <code>yaml_new</code> would be some hook method called when an object is found of some type if that method existed on the class.  But again I can't actually get this to work.  Below is a sample:</p>
  
  <pre><code>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
  </code></pre>
  
  <p><strong>updates</strong></p>
  
  <p>So after playing around in my Rails application, it appears that <code>yaml_new</code> <em>does</em> actually get called from <code>YAML.load</code>.  I have a file in there like so:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Which is just what DJ does, except I'm logging the action.  </p>
  
  <pre><code>YAML.load Contact.first.to_yaml
  # =&gt; yaml_new!!!
  </code></pre>
  
  <p>I actually get the logged output!!  </p>
  
  <p>So what am I doing wrong outside of my Rails app??  Is there some other way of getting this method to trigger??  I ask because I'm trying to test this in my own gem and the <code>yaml_new</code> method doesn't trigger, so my tests fail, and yet it actually does work inside Rails</p>