Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to refactor to the new Ruby 1.9 hash syntax [duplicate]

I have a recipe that has the following code that is failing a lint test:

service 'apache' do
  supports :status => true, :restart => true, :reload => true
end

It fails with the error:

Use the new Ruby 1.9 hash syntax.
  supports :status => true, :restart => true, :reload => true

Not sure what the new syntax looks like... can anyone please assist?

like image 578
TyMac Avatar asked May 16 '17 15:05

TyMac


1 Answers

In the Ruby version 1.9 has been introduced a new syntax for hash literals whose keys are symbols. Hashes use the "hash rocket" operator to separate the key and the value:

a_hash = { :a_key => 'a_value' }

In Ruby 1.9 this syntax is valid, but whenever the key is a symbol it's also possible to write it as:

a_hash = { a_key: 'a_value' }

And as the Ruby style guide says, you should prefer to use the Ruby 1.9 hash literal syntax when your hash keys are symbols (see):

# bad
hash = { :one => 1, :two => 2, :three => 3 }

# good
hash = { one: 1, two: 2, three: 3 }

And as an additional hint: Don't mix the Ruby 1.9 hash syntax with hash rockets in the same hash literal. When you've got keys that are not symbols stick to the hash rockets syntax (see):

# bad
{ a: 1, 'b' => 2 }

# good
{ :a => 1, 'b' => 2 }

So you can try with:

service 'apache' do
  supports status: true, restart: true, reload: true
end

If you want to see what's the Rubocop "way" you can run this in the command line, this will autocorrect your code only for the HashSyntax warnings or flags:

rubocop --only HashSyntax --auto-correct
like image 156
Sebastian Palma Avatar answered Sep 30 '22 15:09

Sebastian Palma