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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)