Skip to content

Instantly share code, notes, and snippets.

@ShreyanJain9
Last active June 26, 2023 21:40
Show Gist options
  • Save ShreyanJain9/539123d8f8d91ff980c1828e87410821 to your computer and use it in GitHub Desktop.
Save ShreyanJain9/539123d8f8d91ff980c1828e87410821 to your computer and use it in GitHub Desktop.
A ruby module that instantly turns json into an object
require 'json'
module JSONObject
def self.create(json)
data = JSON.parse(json)
klass = Class.new do
data.each do |key, value|
attr_accessor key.to_sym
define_method(:initialize) { |**args| args.each { |k, v| instance_variable_set("@#{k}", v) } }
end
end
klass.new(data)
end
def self.to_json(obj)
data = {}
obj.instance_variables.each do |var|
key = var.to_s.delete("@").to_sym
data[key] = obj.instance_variable_get(var)
end
JSON.generate(data)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment