Read more

Defining to_json and avoiding errors

Arne Hartherz
October 11, 2011Software engineer at makandra GmbH

Defining a custom to_json method for your classes can be useful. Do it properly or you will "randomly" get errors like these:

wrong number of arguments (1 for 0) (ArgumentError)
wrong number of arguments (0 for 1) (ArgumentError)
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Take a look at how Object#to_json is defined:

def to_json(options = nil)
  ActiveSupport::JSON.encode(as_json(options))
end

Make sure you at least take the options argument -- or, if you don't need to look at it, just grab and (if you need to) pass on any arguments you receive like this:

def to_json(*args, &block)
  my_custom_representation.to_json(*args, &block)
end

That way, outside code can call your to_json method any way they like.

Posted by Arne Hartherz to makandra dev (2011-10-11 14:11)