Sonar quality profiles question

We are seeing a lot of critical quality errors in the ruby quality profile like this:

Define a constant instead of duplicating this literal

For example if we repeat ‘Content-Type’ in a file like this:

param :header, 'Content-Type', :string, :required, 'application/json'

or when we use the i18n translations in the same file:

t('some.translation.value')

What is the best way to deal with these so that Sonar does not complain? It doesn’t seem correct to create a constant to contain these strings. Is there some best practice that should be followed for these types of repeatable strings?

I can’t seem to find any documentation on it.

Note that we have no control over the quality profile so we cannot turn it off.

Hi @bingobango ,

Welcome to SonarSource Community! :sonarsource:

You will need to create a constant so that the string literal is not repeated throughout. A simple example from our rules repository for this specific issue you have:

Noncompliant Code Example

With the default threshold of 3:

def foo()
  prepare('action random1')    #Noncompliant - "action random1" is duplicated 3 times
  execute('action random1')
  release('action random1')
end

Compliant Solution

def foo()
  action1 = 'action random1'
  prepare(action1)
  execute(action1)
  release(action1)
end

Exceptions

To prevent generating some false-positives, literals having 5 or less characters are excluded as well as literals containing only letters, digits and ‘_’.

Joe