Created
May 22, 2020 09:54
-
-
Save namnv609/8f55d4adf5699a23df8e952637684179 to your computer and use it in GitHub Desktop.
Dynamic create Struct class in Ruby (pure)
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
users_data = [{ | |
"id": "7c5dae5552338874e5053f2534d2767a", | |
"email": "[email protected]", | |
"first_name": "John", | |
"last_name": "Appleseed", | |
"username": "cfuser12345", | |
"telephone": "+1 123-123-1234", | |
"country": "US", | |
"zipcode": "12345", | |
"created_on": "2014-01-01T05:20:00Z", | |
"modified_on": "2014-01-01T05:20:00Z", | |
"two_factor_authentication_enabled": false, | |
"suspended": false | |
}, | |
{ | |
"id": "7c5dae5552338874e5053f2534d2767a", | |
"email": "[email protected]", | |
"first_name": "John", | |
"last_name": "Appleseed", | |
"username": "cfuser12345", | |
"telephone": "+1 123-123-1234", | |
"country": "US", | |
"zipcode": "12345", | |
"created_on": "2014-01-01T05:20:00Z", | |
"modified_on": "2014-01-01T05:20:00Z", | |
"two_factor_authentication_enabled": false, | |
"suspended": false | |
}]; | |
def create_class class_name, attrs | |
unless Object.const_defined?(class_name) | |
Object.const_set class_name, Struct.new(*attrs) | |
end | |
end | |
users = users_data.map do |user| | |
create_class "User", user.keys | |
Object.const_get("User").new *user.values | |
end | |
p users.first |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment