Skip to content

Commit 38a2ad0

Browse files
authored
Merge pull request rubocop#931 from r7kamura/feature/presense-multiline-ternary
Fix error in `Rails/Presence` when ternary operators are used in multiple lines
2 parents fd69f79 + fc38085 commit 38a2ad0

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#931](https://github.com/rubocop/rubocop-rails/pull/931): Fix error in `Rails/Presence` when ternary operators are used in multiple lines. ([@r7kamura][])

lib/rubocop/cop/rails/presence.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,10 @@ def message(node, receiver, other)
112112
end
113113

114114
def current(node)
115-
if node.source.include?("\n")
115+
if !node.ternary? && node.source.include?("\n")
116116
"#{node.loc.keyword.with(end_pos: node.condition.loc.selector.end_pos).source} ... end"
117117
else
118-
node.source
118+
node.source.gsub(/\n\s*/, ' ')
119119
end
120120
end
121121

spec/rubocop/cop/rails/presence_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,21 @@
233233
RUBY
234234
end
235235

236+
context 'when multiline ternary can be replaced' do
237+
it 'registers an offense and corrects' do
238+
expect_offense(<<~RUBY)
239+
a.present? ?
240+
^^^^^^^^^^^^ Use `a.presence` instead of `a.present? ? a : nil`.
241+
a :
242+
nil
243+
RUBY
244+
245+
expect_correction(<<~RUBY)
246+
a.presence
247+
RUBY
248+
end
249+
end
250+
236251
context 'when a method argument of `else` branch is enclosed in parentheses' do
237252
it 'registers an offense and corrects' do
238253
expect_offense(<<~RUBY)

0 commit comments

Comments
 (0)