diff --git a/changelog/fix_error_in_rails_presence_when_ternary.md b/changelog/fix_error_in_rails_presence_when_ternary.md new file mode 100644 index 0000000000..131e303043 --- /dev/null +++ b/changelog/fix_error_in_rails_presence_when_ternary.md @@ -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][]) diff --git a/lib/rubocop/cop/rails/presence.rb b/lib/rubocop/cop/rails/presence.rb index ac1e69c185..6a134736ae 100644 --- a/lib/rubocop/cop/rails/presence.rb +++ b/lib/rubocop/cop/rails/presence.rb @@ -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 diff --git a/spec/rubocop/cop/rails/presence_spec.rb b/spec/rubocop/cop/rails/presence_spec.rb index 898ecf9fff..93cf6ab707 100644 --- a/spec/rubocop/cop/rails/presence_spec.rb +++ b/spec/rubocop/cop/rails/presence_spec.rb @@ -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)