[colug-432] deserialize objects in Ruby

Rick Hornsby 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).

Long version:

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)
    \_ AmazonSong
    \_ SpotifySong
    \_ YoutubeSong
    \_ etc

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[1][2].  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.

thanks!


[1] https://gist.github.com/rjhornsby/72fb3b6057d0d747246d
[2] https://gist.github.com/rjhornsby/84d0e1481216808c18f7




More information about the colug-432 mailing list