views:

205

answers:

3

Does to_json require parameters? what about within rails?

I started getting the error "wrong number of arguments (0 for 1)" when doing myhash.to_json

Unfortunately I'm not sure when this error started happening, but I guess it relates to some versions of either rails or the json gem. I suppose my code (in a rails controller) is using the ActiveSupport::JSON version of to_json, rather than the to_josn method supported by the json gem. ActiveSupport::JSON vs JSON

In environment.rb I have

RAILS_GEM_VERSION = '2.3.2'

and also

config.gem "json", :version=> '1.1.7'

It's just a simple hash structure containing primitives which I want to convert in my controller, and it was working, but now I can't seem to run to_json without passing parameters.

A: 

Do you have your own version of to_json defined in a model that doesn't take args? If so, make it accept *args or opts = {}

x1a4
A: 

If ActiveSupport in that version of rails has to_json, why use a gem? The Gem probably redefines Object#to_json to require arguments and thats why you are getting an error.

Look in the code of the json Gem and find where to_json is defined to verify this.

Daniel Beardsley
Thanks. You're right, I didn't want to use the gem within that controller. I was confused about whether or it was *trying* to use the gem. All sorted now though.
Harry Wood
A: 

to_json does not require parameters, when you're using the version provided within rails (ActiveSupport::JSON) So that error message shows that it must be trying to call the to_josn method defined in the json gem.

So my actual source of confusion was around the way rails loads these libraries.

It will load the json gem and use it within a controller, even if I don't have a line saying 'require json' because rails loads gems as defined in environment.rb, so in fact I needed to remove the line

config.gem "json", :version=> '1.1.7'

...from my environment.rb . My code had been broken since I had added that. Confusingly I do need that gem, but only for scripting I'm doing outside of rails.

Harry Wood
...Although I do still have a mystery around why it this line didn't break things on my server, only on my local machine.
Harry Wood