I’m using DataMapper in a Rails project, and have found that calling to_json on either a model instance or collection results in weird behavior: either a circular reference error from JSON, or an infinite series of the same query.
Assuming this was a problem with my model definitions, I opened a Rails console and created the simplest possible model:
class Foo
include DataMapper::Resource
property :id, Serial
property :name, String
end
Foo.auto_migrate! # create db table `foos` for this model
After saving an instance of this model, I did this:
f = Foo.first
f.to_json
At this point, the process appears to hang. If I tail -f log/development.log, I see this query executing over and over:
SQL (0.084ms) SELECT `id`, `name` FROM `foos` ORDER BY `id`
Ruby’s memory usage continues to grow until I interrupt the command or kill the Ruby process. This is the same problem I had with my actual models, so I don’t think it was related to a wrong model definition.
What causes this bizarre behavior?
It seems that the Object#to_json method, as implemented by ActiveSupport, serializes all the attributes of the object. Datamapper maintains a self-referential variable (@_repository) that sends the method into a recursive tailspin.
Good news is that the dm-serializer gem (as you mentioned) provides the necessary functionality, and the Rails has already stated how to fix the problem in the dm-rails project (it just hasn’t happened yet).