Created
April 3, 2015 19:40
-
-
Save MartinHeimbring/e65bc2bb4d2446e16092 to your computer and use it in GitHub Desktop.
Automate creating a #to_json method for an object (in order to serialize the properties) by inheriting from a class that does exactly this
This file contains hidden or 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
| class JSONable | |
| # serialize object to json | |
| def to_json | |
| hash = Hash.new | |
| self.instance_variables.each do |ivar| | |
| hash[ivar] = self.instance_variable_get ivar | |
| end | |
| hash.to_json | |
| end | |
| # copy the saved state that was saved as the JSON string to the object | |
| def from_json! json_string | |
| JSON.load(json_string).each do |ivar, val| | |
| self.instance_variable_set ivar, val | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment