Skip to content

Commit 01d3e9d

Browse files
authored
Merge pull request #14065 from lovro-bikic/redundant-type-conversion-to-json-to-s
Make `Lint/RedundantTypeConversion` register an offense for `to_json.to_s`
2 parents 237a95e + bc3f2a6 commit 01d3e9d

File tree

3 files changed

+9
-4
lines changed

3 files changed

+9
-4
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#14065](https://github.com/rubocop/rubocop/pull/14065): Update `Lint/RedundantTypeConversion` to register an offense for `to_json.to_s`. ([@lovro-bikic][])

lib/rubocop/cop/lint/redundant_type_conversion.rb

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ module Lint
2727
# In all cases, chaining one same `to_*` conversion methods listed above is redundant.
2828
#
2929
# The cop can also register an offense for chaining conversion methods on methods that are
30-
# expected to return a specific type regardless of receiver (eg. `foo.inspect.to_s`).
30+
# expected to return a specific type regardless of receiver (eg. `foo.inspect.to_s` and
31+
# `foo.to_json.to_s`).
3132
#
3233
# @example
3334
# # bad
@@ -69,10 +70,12 @@ module Lint
6970
# foo.to_s
7071
#
7172
# # bad - chaining a conversion to a method that is expected to return the same type
72-
# inspect.to_s
73+
# foo.inspect.to_s
74+
# foo.to_json.to_s
7375
#
7476
# # good
75-
# inspect
77+
# foo.inspect
78+
# foo.to_json
7679
#
7780
class RedundantTypeConversion < Base
7881
extend AutoCorrector
@@ -108,7 +111,7 @@ class RedundantTypeConversion < Base
108111

109112
# Methods that already are expected to return a given type, which makes a further
110113
# conversion redundant.
111-
TYPED_METHODS = { to_s: %i[inspect] }.freeze
114+
TYPED_METHODS = { to_s: %i[inspect to_json] }.freeze
112115

113116
CONVERSION_METHODS = Set[*LITERAL_NODE_TYPES.keys].freeze
114117
RESTRICT_ON_SEND = CONVERSION_METHODS + [:to_d]

spec/rubocop/cop/lint/redundant_type_conversion_spec.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@
192192
it_behaves_like 'offense', :to_s, %('string'), '.bar'
193193

194194
it_behaves_like 'chained typed method', :to_s, 'inspect'
195+
it_behaves_like 'chained typed method', :to_s, 'to_json'
195196

196197
it 'registers an offense and corrects with a heredoc' do
197198
expect_offense(<<~RUBY)

0 commit comments

Comments
 (0)