Skip to content

Commit af30389

Browse files
authored
Merge pull request #1255 from Earlopain/fix-error-for-rails-unique-before-pluck
Fix an error for `Rails/UniqBeforePluck` with `EnforcedStyle: aggressive` when no receiver
2 parents 650e783 + b849c60 commit af30389

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1255](https://github.com/rubocop/rubocop-rails/pull/1255): Fix an error for `Rails/UniqBeforePluck` with `EnforcedStyle: aggressive` when no receiver. ([@earlopain][])

lib/rubocop/cop/rails/uniq_before_pluck.rb

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,23 @@ def on_send(node)
6868
return unless uniq
6969

7070
add_offense(node.loc.selector) do |corrector|
71-
method = node.method_name
72-
73-
corrector.remove(dot_method_with_whitespace(method, node))
74-
corrector.insert_before(node.receiver.loc.dot.begin, '.distinct')
71+
autocorrect(corrector, node)
7572
end
7673
end
7774

7875
private
7976

77+
def autocorrect(corrector, node)
78+
method = node.method_name
79+
80+
corrector.remove(dot_method_with_whitespace(method, node))
81+
if (dot = node.receiver.loc.dot)
82+
corrector.insert_before(dot.begin, '.distinct')
83+
else
84+
corrector.insert_before(node.receiver, 'distinct.')
85+
end
86+
end
87+
8088
def dot_method_with_whitespace(method, node)
8189
range_between(dot_method_begin_pos(method, node), node.loc.selector.end_pos)
8290
end

spec/rubocop/cop/rails/uniq_before_pluck_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,5 +113,16 @@
113113
instance.assoc.distinct.pluck(:name)
114114
RUBY
115115
end
116+
117+
it 'corrects uniq when used without a receiver' do
118+
expect_offense(<<~RUBY)
119+
pluck(:name).uniq
120+
^^^^ Use `distinct` before `pluck`.
121+
RUBY
122+
123+
expect_correction(<<~RUBY)
124+
distinct.pluck(:name)
125+
RUBY
126+
end
116127
end
117128
end

0 commit comments

Comments
 (0)