The need their own #to_json
method defined so that they output “typed values” instead of #to_s
by default. Similar to how the API #inspect
overrides work …
Geom::Point3d.new(1,2,3).inspect.to_json
#=> "Point3d(1, 2, 3)"
Then JSON needs to know how to convert back using the class name, calling it’s constructor passing in the arguments.
The JSON library is designed to be expanded by adding class conversion definitions to the following directory:
"<rubylib>/json/lib/json/add"
You wouldn’t think ordinarily that Ruby Exception
classes would be JSON compatible, but take a look at:
"<rubylib>/json/lib/json/add/exception.rb"
… and you’ll get the idea quickly as there are only 3 methods to define.