Skip to content

Instantly share code, notes, and snippets.

@esquinas
Last active May 7, 2021 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esquinas/85df587f7faa05095a2ff4414cfb59b8 to your computer and use it in GitHub Desktop.
Save esquinas/85df587f7faa05095a2ff4414cfb59b8 to your computer and use it in GitHub Desktop.
Example for Ruby JSON.parse option create_additions?
require 'json'
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def to_json(options = {})
{
'json_class' => self.class.name,
'data' => { 'name' => name, 'age' => age },
}.to_json(options)
end
def self.json_create(a_hash)
new(a_hash['data']['name'], a_hash['data']['age'])
end
end
alice = Person.new 'Alice', 42 # => #<Person:0x0000... @name="Alice", @age=42>
jsoned_alice = alice.to_json # => '{"json_class": "Person", "data": {"name": "Alice", "age": 42}}'
jsoned_alice = JSON.generate(alice) # => '{"json_class": "Person", "data": {"name": "Alice", "age": 42}}' (Same)
reconstructed_alice = JSON.parse jsoned_alice, create_additions: true # => #<Person:0x0000... @name="Alice", @age=42>
reconstructed_alice.name # => "Alice"
alice.name # => "Alice"
reconstructed_alice.name == alice.name # => true
reconstructed_alice.age == alice.age # => true
reconstructed_alice == alice # => false
reconstructed_alice.object_id == alice.object_id # => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment