Skip to content

Instantly share code, notes, and snippets.

@chrisronline
Last active August 29, 2015 14:05
Show Gist options
  • Save chrisronline/be11e49bb56a6794280a to your computer and use it in GitHub Desktop.
Save chrisronline/be11e49bb56a6794280a to your computer and use it in GitHub Desktop.
require 'json'
class JSONSerializer
def self.deserialize(json, cls)
obj = cls.new()
parsed = JSON.parse(json)
parsed.each do |child|
prop = child[0]
value = child[1]
obj.send("#{prop}=", value)
end
obj
end
end
class JSONModel
attr_accessor :data
def initialize
@data = {}
end
def method_missing(name, *arguments)
value = arguments[0]
name = name.to_s
#puts "method_missing '#{name}', '#{name[-1, 1]}'"
# if the method's name ends with '='
if name[-1, 1] == "="
method_name = name[0..-2]
#puts "Setting '#{method_name}' to '#{value}'"
@data[method_name] = value
else
#puts "Getting '#{name}'"
@data[name]
end
end
end
class Account < JSONModel
end
class Entity < JSONModel
end
str = '{"id": 1, "firstName": "Chris", "lastName": "Roberson"}'
account = JSONSerializer.deserialize(str, Account)
puts account.class
puts "#{account.firstName} #{account.lastName}"
entity = JSONSerializer.deserialize(str, Entity)
puts entity.class
puts "#{entity.firstName} #{entity.lastName}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment