-
Notifications
You must be signed in to change notification settings - Fork 0
Serializer Deserializer
Often times in a program there is a persistence engine that stores information. The format of the data the program takes as input may not be the same as the program's output.
Example: A server might take a structured query language as input, and return JSON as output.
Example: Casper has a web application. Casper wants to allow the users to access the application from an iPhone so Casper builds an HTTP API. Then Casper writes code so that the iPhone communicates with the application for information. While Casper stores the information as a YAML flat file Casper wants the over-the-wire communication to be JSON, since the iPhone has a native JSON parser.
It is common to have both a serializer (the process of turning the native format into the desired exterior format) and a deserializer (the process of turning accepted exterior format into native format).
In Ruby this might look like:
class Deserializer
DEFAULTS = {}
def initialize(raw, options)
@raw = raw
@options = DEFAULTS.merge(options)
end
def to_h
JSON.load(@raw, @options)
end
end
input = %|{ "name": "Kurtis Rainbolt-Greene", "age": 26 }|
storage << Deserializer.new(input, {}).to_h
class Serializer
DEFAULTS = {}
def initialize(hash, options)
@hash = hash
@options = DEFAULTS.merge(options)
end
def to_s
YAML.dump(@hash, @options)
end
end
output = Serializer.new(storage).to_s
# ---
# name: "Kurtis Rainbolt-Greene"
# age: 26
Software Pattern Language Wiki by The Pattern Language Group is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. Based on a work at http://github.com/pattern-langauge/software/wiki.