Last active
August 29, 2015 14:14
-
-
Save asterite/0467f974cdfe27ed8f15 to your computer and use it in GitHub Desktop.
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" | |
class Object | |
macro def_find_by_name | |
{{:macro.id}} def self.find_by_name(name) : {{@type.name.id}}.class | |
case name | |
\{% for subclass in {{@type.name.id}}.all_subclasses %} | |
when \{{subclass.name}} | |
\{{subclass.name.id}} | |
\{% end %} | |
else | |
raise "Can't find {{@type.name.id}} by this name: #{name}" | |
end | |
end | |
end | |
end | |
class JSON::KeyRegistry(T) | |
def self.new(pull : JSON::PullParser) | |
plugins = [] of T | |
pull.read_object do |key| | |
plugins << T.find_by_name(key).new(pull) | |
end | |
plugins | |
end | |
end | |
abstract class Plugin | |
def_find_by_name | |
end | |
class PluginOne < Plugin | |
json_mapping({one: String}) | |
end | |
class PluginTwo < Plugin | |
json_mapping({two: String}) | |
end | |
class Config | |
json_mapping({plugins: JSON::KeyRegistry(Plugin)}) | |
end | |
json = %( | |
{ | |
"plugins": { | |
"PluginOne": { | |
"one": "HOLA" | |
}, | |
"PluginTwo": { | |
"two": "CHAU" | |
} | |
} | |
} | |
) | |
config = Config.from_json(json) | |
pp config | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment