Giter Club home page Giter Club logo

serializable's Introduction

Atom and all repositories under Atom will be archived on December 15, 2022. Learn more in our official announcement

Serializable Build Status

This npm provides a Serializable mixin to streamline the process of writing serializable classes. Include the mixin and implement two instance methods (::serializeParams and ::deserializeParams) to add serialization to your class.

Using Serializable Classes

Basics

Before digging into how to implement serializable classes, let's touch on how to use them. To serialize an object, call ::serialize. To deserialize an object, call .deserialize on its class with the results of a previous call to ::serialize.

train1 = new Train(cars: 20, hasCaboose: true)
train1State = train1.serialize()
train2 = Train.deserialize(train1State)
expect(train2.cars).toBe 20
expect(train2.hasCaboose).toBe true

Extra Deserialize Params

You can pass .deserialize an optional second argument containing additional non-serializable parameters which will be merged with the deserialized parameters when constructing the object. For example, say that trains need a reference to a RailNetwork instance, but that the RailNetwork isn't serialized as part of Train:

train1 = new Train(cars: 20, hasCaboose: true, railNetwork: network)
train1State = train1.serialize() # does not contain a serialized RailNetwork
train2 = Train.deserialize(train1State, railNetwork: network)

Implementing Serializable Classes

Including the Mixin

The Serializable mixin is implemented with the mixto npm. To include it, use the .includeInto class method or simply subclass Serializable.

Serializable = require 'serializable'

class Automobile extends Vehicle
  Serializable.includeInto(this)

::serializeParams()

This method should return a plain JavaScript object containing the serialized version of all parameters required to reconstruct the object.

class Automobile extends Vehicle
  Serializable.includeInto(this)

  constructor: (@doors=4, @engine='v8') ->

  serializeParams: -> {@doors, @engine}

If all your parameters are scalars, this is all that's required. When deserializing, Serializable will match up the names of the keys in the params hash with the names of your constructor parameters to reconstruct your object.

auto1 = new Automobile(2, 'v6')
auto2 = Automobile.deserialize(auto1.serialize())
expect(auto2.doors).toBe 2
expect(auto2.engine).toBe 'v6'

You can also take a params hash as your constructor argument, in which case Serializable won't attempt to match up constructor parameter names.

class Train extends Vehicle
  Serializable.includeInto(this)

  constructor: ({@cars, @hasCaboose}={}) ->

  serializeParams: -> {@cars, @hasCaboose}

::deserializeParams(params)

If your params hash contains nested serialized objects, you'll need to deserialize the nested objects before they are passed to the constructor of the parent object. You perform this deserialization in the optional ::deserializeParams instance method.

class Plane extends Vehicle
  constructor: (@engines, @pilot) ->
    @pilot ?= new Pilot(name: "Bob", plane: this)

  serializeParams: -> {@engines, pilot: @pilot.serialize()}

  deserializeParams: (params) ->
    params.pilot = Pilot.deserialize(params.pilot, plane: this)
    params

Using some JS trickery, this method is called before your object's constructor, allowing you to reference the instance being deserialized when deserializing its children. You can also perform pre-initialization in this method. Note that it is safe to modify the params object that is passed into your method. This is convenient when only a subset of your params need to be deserialized.

Polymorphic Deserialization

If you can't know the specific class of the object you are deserializing ahead of time, you can call ::registerDeserializers on a superclass (or any serializable class) to enable polymorphic deserialization.

Vehicle.registerDeserializers(Plane, Train)
Vehicle.registerDeserializer(Automobile)

vehicleStates = [plane, train, auto].map (vehicle) -> vehicle.serialize()
vehicles = vehicleStates.map (vehicleState) -> Vehicle.deserialize(vehicleState)

serializable's People

Contributors

darangi avatar dbkaplun avatar kevinsawicki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serializable's Issues

Test failure on Node 4 "node: bad option: --harmony_collections"

$ npm test

> [email protected] test /Users/dan/stuff/serializable
> grunt test

Running "coffee:glob_to_multiple" (coffee) task
File lib/serializable.js created.

Running "coffeelint:src" (coffeelint) task
>> 1 file lint free.

Running "coffeelint:test" (coffeelint) task
>> 2 files lint free.

Running "coffeelint:gruntfile" (coffeelint) task
>> 1 file lint free.

Running "shell:test" (shell) task
node: bad option: --harmony_collections
Warning: Command failed: /bin/sh -c node --harmony_collections node_modules/.bin/jasmine-focused --coffee --captureExceptions spec
node: bad option: --harmony_collections
 Use --force to continue.

Aborted due to warnings.
npm ERR! Test failed.  See above for more details.

npm ERR! Path must be a string. Received undefined

This is likely due to serializable depending on an old version of get-parameter-names, which in turn depends on testla which fails to install. npm-debug.log

$ npm install serializable
npm ERR! Darwin 14.5.0
npm ERR! argv "/usr/local/bin/iojs" "/usr/local/bin/npm" "install" "serializable"
npm ERR! node v4.1.1
npm ERR! npm  v3.3.5

npm ERR! Path must be a string. Received undefined
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/dan/npm-debug.log

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.