
to_json crashes with has of collections
Reported by Gibheer | September 16th, 2010 @ 02:47 PM
I tried to generate a json_file of two datamapper collections,
but it crashed with the message "#<NoMethodError: undefined
method merge' for
#<JSON::Ext::Generator::State:0x00000801e8c4a8>>"
Here is a little testcase for showing the problem. The problem lies in opts, which sometimes is a JSON::Status object, which can't be converted to a propert hash.
edit: the file for the fix is dm-serializer/lib/dm-serializer/to_json.rb
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
require 'dm-serializer'
DataMapper.setup(:default, 'sqlite://:memory:')
class A
include DataMapper::Resource property :id, Serial has n, :bs
end
class B
include DataMapper::Resource property :id, Serial belongs_to :a
end
DataMapper.finalize
DataMapper.auto_migrate!
p "without fix, it crashes"
begin
{:b => B.all, :a => B.all.as}.to_json rescue NoMethodError
=> e
p e.inspect end
p "now the fix"
module DataMapper
class Collection
def to_json(*args)
opts = args.first || {}
# the fix
opts = {} unless opts.respond_to? :merge
options = opts.merge(:to_json => false)
collection = map { |e| e.to_json(options) }
# default to making JSON
if opts.fetch(:to_json, true)
collection.to_json
else
collection
end
end
end end
{:b => B.all, :a => B.all.as}.to_json p "works"
Comments and changes to this ticket
-
humancyborg September 17th, 2010 @ 06:24 PM
Thanks for this, I arrived at the same conclusion (and the exact same fix funnily enough) today as well.
The root problem is really that #<JSON::Ext::Generator::State:0x9281bb8> should not be coming in as args in the first place, but this patch solves it for now.
-
Dan Kubb (dkubb) September 17th, 2010 @ 10:56 PM
- State changed from new to resolved
(from [817b8ddd7d3f60f44b8aaf662b8dd78f289df567]) Fixed problem with JSON::Ext::Generator::State passed in for #to_json options
- The old code assumed that the object passed in was either nil or a Hash, or something that can be coerced into a Hash. However, in certain cases, such as when JSON itself is handling serialization, it will pass in a JSON::Ext::Generator::State object. This fix will ignore anything other than a Hash passed in.
[#1412 state:resolved] [#1360 state:resolved] http://github.com/datamapper/dm-serializer/commit/817b8ddd7d3f60f44...
Please Sign in or create a free account to add a new ticket.
With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
People watching this ticket
Referenced by
-
1412 to_json crashes with has of collections [#1412 state:resolved] [#1360 state:resolved] http://git...
-
1360 to_json in dm-serializers throws exceptions on included associations. [#1412 state:resolved] [#1360 state:resolved] http://git...