Skip to content

Instantly share code, notes, and snippets.

@bluurn
Last active March 26, 2019 12:56
Show Gist options
  • Save bluurn/467afcc86a6640433642436bb85356de to your computer and use it in GitHub Desktop.
Save bluurn/467afcc86a6640433642436bb85356de to your computer and use it in GitHub Desktop.
Ruby: Implement SerializableStruct
require 'json'
module SerializableStruct
class Dummy
def self.members
@members
end
def initialize(*vals)
vals.each_with_index do |val, idx|
send("#{self.class.members[idx]}=", val)
end
end
def to_h
self.class.members.each_with_object({}) do |it, acc|
val = send(it)
acc[it] = val.is_a?(Dummy) ? val.to_h : val
end
end
def to_json
to_h.to_json
end
def hash
to_h.hash
end
end
def self.new(*members)
Class.new(Dummy) do
@members = members
attr_accessor *members
yield self if block_given?
end
end
end
Parent = SerializableStruct.new(:child1, :child2) do
Child1 = SerializableStruct.new(:name, :surname)
Child2 = SerializableStruct.new(:name, :nickname)
end
structure = Parent.new(
Child1.new("test", "good"),
Child2.new("haha", "hehe")
)
puts structure.to_json
# Outputs: {"child1":{"name":"test","surname":"good"},"child2":{"name":"haha","nickname":"hehe"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment