Skip to content

Commit

Permalink
Make Style/EmptyHeredoc aware of EnforcedStyle of `Style/StringLi…
Browse files Browse the repository at this point in the history
…terals`

Follow up #10820 (comment).
  • Loading branch information
koic committed Jul 22, 2022
1 parent 6a2f556 commit 743f6f7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/rubocop/cop/style/empty_heredoc.rb
Expand Up @@ -48,11 +48,25 @@ def on_heredoc(node)
add_offense(node) do |corrector|
heredoc_end = node.loc.heredoc_end

corrector.replace(node, "''")
corrector.replace(node, preferred_string_literal)
corrector.remove(range_by_whole_lines(heredoc_body, include_final_newline: true))
corrector.remove(range_by_whole_lines(heredoc_end, include_final_newline: true))
end
end

private

def preferred_string_literal
enforce_double_quotes? ? '""' : "''"
end

def enforce_double_quotes?
string_literals_config['EnforcedStyle'] == 'double_quotes'
end

def string_literals_config
config.for_cop('Style/StringLiterals')
end
end
end
end
Expand Down
18 changes: 18 additions & 0 deletions spec/rubocop/cop/style/empty_heredoc_spec.rb
Expand Up @@ -68,4 +68,22 @@
EOS
RUBY
end

context 'when double-quoted string literals are preferred' do
let(:other_cops) do
super().merge('Style/StringLiterals' => { 'EnforcedStyle' => 'double_quotes' })
end

it 'registers an offense when using empty `<<~EOS` heredoc' do
expect_offense(<<~RUBY)
<<~EOS
^^^^^^ Use an empty string literal instead of heredoc.
EOS
RUBY

expect_correction(<<~RUBY)
""
RUBY
end
end
end

0 comments on commit 743f6f7

Please sign in to comment.