rubocop / ruby-style-guide

A community-driven Ruby coding style guide
https://rubystyle.guide
16.47k stars 3.4k forks source link

Good practice - Heredocs in hash #871

Closed HS-157 closed 3 years ago

HS-157 commented 3 years ago

Huhu,

I have a multi-line string and I use a heredoc in hash for a cookbook Chef. For check style, I use Cookstyle as linting tool, it raise Style/TrailingCommaInHashLiteral as warning cops.

I would like to know if this is a good practice add comma after first line delimiter when a heredoc use in a hash like add a parenthesis when it's use as argument in a function.

Thank you.

Example

Cookstyle warning

a = {
  toto: 'toto',
  tutu: 'tutu',
  titi: <<~EOS
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Nam euismod erat eget lorem dignissim ornare.
  Ut pellentesque nisi nec ipsum sagittis volutpat vel vitae lorem.
  EOS
}
hs-157@cassiopeia> cookstyle test.rb
Inspecting 1 file
C

Offenses:

test.rb:4:3: C: [Correctable] Style/TrailingCommaInHashLiteral: Put a comma after the last item of a multiline hash.
  titi: <<~EOS
  ^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense auto-correctable

Cookstyle OK

a = {
  toto: 'toto',
  tutu: 'tutu',
  titi: <<~EOS,
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Nam euismod erat eget lorem dignissim ornare.
  Ut pellentesque nisi nec ipsum sagittis volutpat vel vitae lorem.
  EOS
}
hs-157@cassiopeia> cookstyle test.rb
Inspecting 1 file
.

1 file inspected, no offenses detected
pirj commented 3 years ago

But why if it's also a last element?

a = {
  toto: 'toto',
  titi: <<~EOS
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Nam euismod erat eget lorem dignissim ornare.
  Ut pellentesque nisi nec ipsum sagittis volutpat vel vitae lorem.
  EOS,
  tutu: 'tutu'
 }

Would that cop flag this code and suggest changing to this?

a = {
  toto: 'toto',
-  titi: <<~EOS
+  titi: <<~EOS,
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Nam euismod erat eget lorem dignissim ornare.
  Ut pellentesque nisi nec ipsum sagittis volutpat vel vitae lorem.
-  EOS,
+  EOS
  tutu: 'tutu'
 }
pirj commented 3 years ago

Closing as stale