Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

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

Closed
floehopper opened this Issue · 2 comments

2 participants

@floehopper

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?

@tenderlove
Owner

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 tenderlove closed this
@floehopper

Thanks. :+1:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.