Serializing an object for JSON, XML, YAML?

I asked the previous question about serialization and validation. Someone mentioned the use of the JSON pearl, which allows me to tell my object how to serialize using the to_json method, however, Ruby seems to make a lot of complicated things very easy, however, on the other hand, some really simple things seem pretty complicated. Serialization is one of those things.

I want to find out if there is a way to have a clean object:

 class CleanClass attr_accessor :variable1 attr_accessor :variable2 attr_accessor :variable3 end cleanObject = CleanClass.new 

Ideally, I don’t want to pollute the model, I just want to pass it on to something and tell her what the type of output should be, and let it work with my magic.

An example would be something like:

 jsonOutput = MagicSerializer::Json.Serialize(cleanObject) xmlOutput = MagicSerializer::Xml.Serialize(cleanObject) yamlOutput = MagicSerializer::Yaml.Serialize(cleanObject) revertedJsonObject = MagicSerializer::Json.Unserialize(jsonOutput) revertedXmlObject = MagicSerializer::Xml.Unserialize(xmlOutput) revertedYamlObject = MagicSerializer::Yaml.Unserialize(yamlOutput) 

I want to pass something to an object and get the lines printed, and then return it back.

I know that ActiveModel has serialization functions, but I need to foul my class to do this, and I don't want to change the model if possible. ActiveSupport seems to satisfy the JSON criteria, as I can just call it and it will take an object and spit out JSON, but I would like to support other types.

Any additional information would be great!

+6
source share
3 answers

Ruby has built-in automatic serialization / deserialization for binary and yaml.

YAML:

 require 'yaml' serialized = CleanClass.new.to_yaml object = YAML.load(serialized) 

Marshal:

 serialized = Marshal.dump(CleanClass.new) object = Marshal.load(serialized) 
+11
source

For JSON and YAML, this looks pretty easy, as they will only be wrappers for the to_yaml and to_json (or YAML.load and from_json respectively)

For JSON, you will have to wrap your own classes around core-Types (or other types that implement to_json), for example. we first implement the to_hash method, which can then be converted to json.

XML is much more complex due to the hierarchical aspect, you will have to standardize it, but in fact I don’t understand from your explanation of what's wrong with the basic methods to_... This is actually the convention we use in Ruby. If you are concerned about model pollution, you can put these methods in a module and include the module in a class.

 module Foo def to_serialized_type ... end end class CleanClass include Foo end 
+1
source

Ask your magic serialization method to foul an object for you; emdirtering can occur based on each object.

Or dirty at the level of your class.

In any case, your main line code does not see it.

+1
source

Source: https://habr.com/ru/post/900197/


All Articles