Is there a way to mark a class as un-serializable? #112

Closed
floehopper opened this Issue Jan 4, 2013 · 2 comments

Comments

Projects
None yet
2 participants

I'd like YAML.dump to fail fast if it tries to serialize an instance of a specific class.

This was possible with the old syck engine by overriding the #to_yaml method and raising a TypeError.

Is there a way to achieve something similar with psych?

Owner

tenderlove commented Jul 5, 2013

If you define encode_with and make it raise an exception, then Psych will blow up:

>> class Foo; def encode_with(coder); raise TypeError, "can't encode Foo"; end end
=> nil
>> require 'psych'
=> true
>> Psych.dump Foo.new
TypeError: can't encode Foo
    from (irb):1:in `encode_with'
    from /Users/aaron/.rbenv/versions/2.1.0-dev/lib/ruby/2.1.0/psych/visitors/yaml_tree.rb:469:in `dump_coder'
    from /Users/aaron/.rbenv/versions/2.1.0-dev/lib/ruby/2.1.0/psych/visitors/yaml_tree.rb:146:in `accept'
    from /Users/aaron/.rbenv/versions/2.1.0-dev/lib/ruby/2.1.0/psych/visitors/yaml_tree.rb:112:in `push'
    from /Users/aaron/.rbenv/versions/2.1.0-dev/lib/ruby/2.1.0/psych.rb:408:in `dump'
    from (irb):3
    from /Users/aaron/.rbenv/versions/2.1.0-dev/bin/irb:11:in `<main>'
>> 

I'll add a more specific exception in the future, but this will do the trick for now. Hope that helps!

tenderlove closed this Jul 5, 2013

Thanks. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment