Skip to content

Commit

Permalink
Merge pull request #931 from r7kamura/feature/presense-multiline-ternary
Browse files Browse the repository at this point in the history
Fix error in `Rails/Presence` when ternary operators are used in multiple lines
  • Loading branch information
koic authored Feb 10, 2023
2 parents fd69f79 + fc38085 commit 38a2ad0
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_error_in_rails_presence_when_ternary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#931](https://github.com/rubocop/rubocop-rails/pull/931): Fix error in `Rails/Presence` when ternary operators are used in multiple lines. ([@r7kamura][])
4 changes: 2 additions & 2 deletions lib/rubocop/cop/rails/presence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ def message(node, receiver, other)
end

def current(node)
if node.source.include?("\n")
if !node.ternary? && node.source.include?("\n")
"#{node.loc.keyword.with(end_pos: node.condition.loc.selector.end_pos).source} ... end"
else
node.source
node.source.gsub(/\n\s*/, ' ')
end
end

Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/rails/presence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,21 @@
RUBY
end

context 'when multiline ternary can be replaced' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
a.present? ?
^^^^^^^^^^^^ Use `a.presence` instead of `a.present? ? a : nil`.
a :
nil
RUBY

expect_correction(<<~RUBY)
a.presence
RUBY
end
end

context 'when a method argument of `else` branch is enclosed in parentheses' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit 38a2ad0

Please sign in to comment.