New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add linting for to_json #6378
Comments
Are you sure the argument is a Hash? require 'json'
class MyClass
def to_json(*args)
p args
""
end
end
JSON.generate(MyClass.new)
#=> [#<JSON::Ext::Generator::State:0x00007faacb155a40>] |
@bquorning thanks for calling that out - it currently returns a hash-like object: https://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-generate from the docs:
Using a default of [6] pry(#<MyClass>)> args
=> #<JSON::Ext::Generator::State:0x00007fc4959e2af8>
[7] pry(#<MyClass>)> args[:indent]
=> " "
[8] pry(#<MyClass>)> args.to_hash
=> {:indent=>" ", :space=>"", :space_before=>"", :object_nl=>"", :array_nl=>"", :allow_nan=>false, :ascii_only=>false, :max_nesting=>100, :depth=>0, :buffer_initial_length=>1024} that said perhaps just an argument with no default is enough, ie: def to_json(_opts)
end What do you think? |
Weird then, that the signature for e.g. I found this old commit on Ruby where the documentation for Perhaps we should just recommend having |
This fixes issue rubocop#6378 classes that override to_json need to ensure an optional argument is available. class MyClass def to_json end end While calling MyClass.new.to_json works, calling JSON.generate(MyClass.new) results in an ArgumentError.
Is your feature request related to a problem? Please describe.
classes that override
to_json
need to ensure an optional parameter isavailable.
While calling
MyClass.new.to_json
works, callingJSON.generate(MyClass.new)
results in anArgumentError
. That's because the rubyJSON
api wants to send additional options (via a hash) toto_json
, ieto_json(opts = {})
Describe the solution you'd like
I'd like a linter to catch this as it's not obvious from the ruby JSON docs.
Describe alternatives you've considered
The text was updated successfully, but these errors were encountered: