Skip to content

Instantly share code, notes, and snippets.

@MartinHeimbring
Created April 3, 2015 19:40
Show Gist options
  • Save MartinHeimbring/e65bc2bb4d2446e16092 to your computer and use it in GitHub Desktop.
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
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