Skip to content

Commit

Permalink
Preserve multiline semantics on Rails/Presence
Browse files Browse the repository at this point in the history
Similar issue: rubocop/rubocop#10784

Before
```diff
if a.present?
+^^^^^^^^^^^^^ Use `a.presence || b.to_f * 12.0` instead of `if a.present?
+  a
+else
+  b
+end`.
  a
else
  b
end
```

After
```diff
if a.present?
+^^^^^^^^^^^^^ Use `a.presence || b` instead of `if a.present? ... end`.
  a
else
  b.to_f + 12.0
end
```
  • Loading branch information
ydah committed Oct 19, 2022
1 parent 7220b5c commit 2dc3825
Show file tree
Hide file tree
Showing 3 changed files with 288 additions and 104 deletions.
@@ -0,0 +1 @@
* [#x](https://github.com/rubocop/rubocop-rails/pull/x): Preserve multiline semantics on `Rails/Presence`. ([@ydah][])
12 changes: 11 additions & 1 deletion lib/rubocop/cop/rails/presence.rb
Expand Up @@ -106,7 +106,17 @@ def ignore_other_node?(node)
end

def message(node, receiver, other)
format(MSG, prefer: replacement(receiver, other), current: node.source)
prefer = replacement(receiver, other).gsub(/^\s*|\n/, '')
current = current(node).gsub(/^\s*|\n/, '')
format(MSG, prefer: prefer, current: current)
end

def current(node)
if node.source.include?("\n")
"#{node.loc.keyword.with(end_pos: node.condition.loc.selector.end_pos).source} ... end"
else
node.source
end
end

def replacement(receiver, other)
Expand Down

0 comments on commit 2dc3825

Please sign in to comment.