Created
January 24, 2017 17:39
-
-
Save neovintage/6ed5d7d53594454f331a9fc155eaccf4 to your computer and use it in GitHub Desktop.
Storable Types for Kemal-Session
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "json" | |
STORABLE_TYPES = [] of Nil | |
class StorageInstance | |
macro finished | |
alias StorableObjects = Union({{ *STORABLE_TYPES }}) | |
end | |
JSON.mapping({ | |
objects: Hash(String, StorableObjects) | |
}) | |
def initialize | |
@objects = {} of String => StorableObjects | |
end | |
def object(key : String, val : StorableObjects) | |
objects[key] = val | |
end | |
def object(key : String) | |
objects[key] | |
end | |
end | |
module StorableObject | |
class NotImplementedException < Exception; end | |
macro included | |
{% STORABLE_TYPES << @type %} | |
macro finished | |
{% if [email protected]?(Object, "from_json") %} | |
{{ raise("StorableObject #{@type} needs to define `from_json`") }} | |
{% end %} | |
{% if [email protected]?(Object, "to_json") %} | |
{{ raise("StoraableObject #{@type} needs to define `to_json`") }} | |
{% end %} | |
end | |
end | |
end | |
class Whatever | |
JSON.mapping({ | |
doit: String | |
}) | |
include StorableObject | |
end | |
class Something | |
JSON.mapping({ | |
blah: String | |
}) | |
include StorableObject | |
def self.something; end | |
def doit | |
1 | |
end | |
end | |
store = StorageInstance.new | |
store.object("first", Whatever.from_json("{\"doit\":\"something\"}")) | |
store.object("second", Something.from_json("{\"blah\":\"so yeah\"}")) | |
string = store.to_json | |
new_store = StorageInstance.from_json(string) | |
puts new_store.object("first").doit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment