[colug-432] deserialize objects in Ruby
richardjhornsby at gmail.com
Fri Sep 25 17:37:42 EDT 2015
Trying to do subclassing in Ruby, something I've done very little of generally. I understand the basic premise "subclass _is a_ superclass", as in "dog is an animal", so class Dog < Animal etc.
Short version: I don't understand how to deserialize a subclass object and its parent (from JSON).
I've got the serialization working, because it looks like the correct JSON data is being stored in my RedisDB. I know my deserialization approach works because I've been using it prior to deciding that I wanted to re-work things into subclasses, when I only had one class. Deserialization still works for the base class as well.
The basic idea is:
Song (base class)
The subclasses are there primarily to provide type-specific support for the Song class. i.e., the AmazonSong class understands how to resolve an Amazon URL into base class properties (title, album, etc), and has a few bits of data unique to the AmazonSong (amazon product ID, etc).
The serialization works via the implementation of to_json and self.json_create methods. The key to the deserialization is after getting the JSON from the RedisDB, this call:
request_data = JSON.parse(request_json, :create_additions => true)
Ruby uses the attribute in the JSON "json_class" to determine what type of object needs to be created.
I'm struggling to understand how to implement self.json_create in the subclass, so that Song also gets fully instantiated. I think I need to call Song's json_create (super.json_create(?)) - but I'm not sure what to call or what arguments I need to pass it? I'm honestly not 100% clear on exactly what is happening with the self.json_create methods - I only have a rough idea.
More information about the colug-432