Tuesday, November 16, 2010

json (_pure) ruins my morning

wrong argument type JSON::Pure::Generator::State (expected Data)

This is what I saw staring back at me from my console this morning when I checked out a project and ran my specs. Specs that had been passing just fine yesterday. The only thing I could think of was that I had added a couple new gems to my gem file, but since I hadn't used them yet surely they couldn't be breaking my test suite?

Well, if you've been a coder for any length of time, by now you should know that the likelihood of a given event contributing to your code failure is inversely proportional to your initial index of suspicion of it's relation.

Fortunately, I didn't have to search long. Googling for "wrong argument type JSON::Pure::Generator::State" quickly turned up this blog post on prettystatemachine that explains the problem. Those gems I'd added? One had "json_pure" as a dependency, so I'll include my own brief version for reference:

ActiveSupport and json_pure both hook into the "to_json" method. ActiveSupport defines to_json for many simple types, but expects fixnum's "to_json" to be handled by Object. json_pure is intercepting that call and not getting the data it wants. Defining "to_json" on fixnum seems to solve the problem.

Hence, I've created an initializer in my rails app called "./initializers/json_patch.rb" and put the following code in it:


class Fixnum
  def to_json(options = nil)
    to_s
  end
end

Specs pass. I would thank "prettystatemachine" by name, but I can't find any reference to the author of the blog. Whoever you are, thanks man.

No comments: