Posted about 8 years ago. Visible to the public.

Defining to_json and avoiding errors

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)

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.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Arne Hartherz
Last edit:
over 4 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more