Skip to content

Instantly share code, notes, and snippets.

@neovintage
Created January 24, 2017 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neovintage/6ed5d7d53594454f331a9fc155eaccf4 to your computer and use it in GitHub Desktop.
Save neovintage/6ed5d7d53594454f331a9fc155eaccf4 to your computer and use it in GitHub Desktop.
Storable Types for Kemal-Session
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 !@type.class.overrides?(Object, "from_json") %}
{{ raise("StorableObject #{@type} needs to define `from_json`") }}
{% end %}
{% if !@type.overrides?(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