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.

Revisions

  1. MartinHeimbring created this gist Apr 3, 2015.
    17 changes: 17 additions & 0 deletions Serialize ruby objects
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    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