/
to_json.rb
50 lines (46 loc) · 1.39 KB
/
to_json.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks to make sure `#to_json` includes an optional argument.
# When overriding `#to_json`, callers may invoke JSON
# generation via `JSON.generate(your_obj)`. Since `JSON#generate` allows
# for an optional argument, your method should too.
#
# @example
# class Point
# attr_reader :x, :y
#
# # bad, incorrect arity
# def to_json
# JSON.generate([x, y])
# end
#
# # good, preserving args
# def to_json(*args)
# JSON.generate([x, y], *args)
# end
#
# # good, discarding args
# def to_json(*_args)
# JSON.generate([x, y])
# end
# end
#
class ToJSON < Base
extend AutoCorrector
MSG = ' `#to_json` requires an optional argument to be parsable ' \
'via JSON.generate(obj).'
def on_def(node)
return unless node.method?(:to_json) && node.arguments.empty?
add_offense(node) do |corrector|
# The following used `*_args` because `to_json(*args)` has
# an offense of `Lint/UnusedMethodArgument` cop if `*args`
# is not used.
corrector.insert_after(node.loc.name, '(*_args)')
end
end
end
end
end
end