Last active
June 26, 2023 21:40
-
-
Save ShreyanJain9/539123d8f8d91ff980c1828e87410821 to your computer and use it in GitHub Desktop.
A ruby module that instantly turns json into an object
This file contains 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' | |
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