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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)