Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: YAML::Tiny can't serialize an object reference. Can I unbless a Moo object into a hashref and yammily serialize that?

by Haarg (Curate)
on Jul 15, 2019 at 09:15 UTC ( #11102872=note: print w/replies, xml ) Need Help??


in reply to YAML::Tiny can't serialize an object reference. Can I unbless a Moo object into a hashref and yammily serialize that?

I would consider unblessing a bad idea. My recommendation would be to provide a method on your class to provide a hashref representation of your object, and use that in the value you send to YAML::Tiny. Moo just uses normal hashref objects, so the method can be pretty simple and just do a shallow clone, without re-blessing the result.

sub as_hashref { return { %{ $_[0] } }; }

This gives you an easy place to change how the object is serialized if you need it in the future, but doesn't over-complicate things. The more "correct" way to do this would involve using an explicit list of attributes and using their accessors, but it isn't really a problem to rely on it being a normal hashref based object. You are breaking encapsulation, but it's your object, so you can choose if that matters to you.

While Moo can work with objects that aren't based on hashrefs or use other non-standard storage, that isn't the default and is something you'd have to explicitly enable with a MooX module.

  • Comment on Re: YAML::Tiny can't serialize an object reference. Can I unbless a Moo object into a hashref and yammily serialize that?
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11102872]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2020-04-10 07:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The most amusing oxymoron is:
















    Results (49 votes). Check out past polls.

    Notices?