Skip to content

Commit f9a3200

Browse files
committed
Fix false-positives that non Rails formats are offended on Rails/ToSWithArgument
1 parent 3d7228e commit f9a3200

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#869](https://github.com/rubocop/rubocop-rails/pull/869): Fix false-positives that non Rails formats are offended on `Rails/ToSWithArgument`. ([@r7kamura][])

lib/rubocop/cop/rails/to_s_with_argument.rb

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,20 +21,57 @@ class ToSWithArgument < Base
2121
extend AutoCorrector
2222
extend TargetRailsVersion
2323

24+
# These types are defined by the following files in ActiveSupport:
25+
# lib/active_support/core_ext/array/conversions.rb
26+
# lib/active_support/core_ext/date/conversions.rb
27+
# lib/active_support/core_ext/date_time/conversions.rb
28+
# lib/active_support/core_ext/numeric/conversions.rb
29+
# lib/active_support/core_ext/range/conversions.rb
30+
# lib/active_support/core_ext/time/conversions.rb
31+
# lib/active_support/time_with_zone.rb
32+
EXTENDED_FORMAT_TYPES = Set.new(
33+
%i[
34+
currency
35+
db
36+
delimited
37+
human
38+
human_size
39+
inspect
40+
iso8601
41+
long
42+
long_ordinal
43+
nsec
44+
number
45+
percentage
46+
phone
47+
rfc822
48+
rounded
49+
short
50+
time
51+
usec
52+
]
53+
)
54+
2455
MSG = 'Use `to_formatted_s` instead.'
2556

2657
RESTRICT_ON_SEND = %i[to_s].freeze
2758

2859
minimum_target_rails_version 7.0
2960

3061
def on_send(node)
31-
return if node.arguments.empty?
62+
return unless rails_extended_to_s?(node)
3263

3364
add_offense(node.loc.selector) do |corrector|
3465
corrector.replace(node.loc.selector, 'to_formatted_s')
3566
end
3667
end
3768
alias on_csend on_send
69+
70+
private
71+
72+
def rails_extended_to_s?(node)
73+
node.first_argument&.sym_type? && EXTENDED_FORMAT_TYPES.include?(node.first_argument.value)
74+
end
3875
end
3976
end
4077
end

spec/rubocop/cop/rails/to_s_with_argument_spec.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@
99
end
1010
end
1111

12+
context 'with unrelated argument' do
13+
it 'does not register an offense' do
14+
expect_no_offenses(<<~RUBY)
15+
10.to_s(2)
16+
RUBY
17+
end
18+
end
19+
1220
context 'with argument' do
1321
it 'registers an offense' do
1422
expect_offense(<<~RUBY)

0 commit comments

Comments
 (0)