rubychef-reciperubocop

Need to refactor to the new Ruby 1.9 hash syntax


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?


Solution

  • A new syntax for hash literals whose keys are symbols was introduced in Ruby 1.9. Hashes commonly 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):

    # non-recommended
    hash = { :one => 1, :two => 2, :three => 3 }
    
    # recommended
    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):

    # non-recommended
    { a: 1, 'b' => 2 }
    
    # recommended
    { :a => 1, 'b' => 2 }
    

    So you could 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