rubocop icon indicating copy to clipboard operation
rubocop copied to clipboard

Lint/SymbolConversion with string interpolation should be a Style cop

Open RossBarnie opened this issue 8 months ago • 3 comments

Is your feature request related to a problem? Please describe.

The following code shows an example of a violation of the Lint/SymbolConversion cop:

prefix = "foo"

symbol = "#{prefix}_bar".to_sym # violation here
symbol_valid = :"#{prefix}_bar" # no violation

The Lint/SymbolConversion cop description says:

Checks for uses of literal strings converted to a symbol where a literal symbol could be used instead.

This may be a misunderstanding on my part but my assumption is that the symbol and symbol_valid variables in the above code are functionally equivalent in that the String must be created and interpolated before the symbol can be created. In that case, this case is a style choice and there is no performance improvement by using the "literal" syntax over the to_sym method.

Describe the solution you'd like

I would like:

  • Lint/SymbolConversion to ignore interpolated strings being converted to a symbol using the to_sym method
  • A new Style cop created to enforce "always use symbol literals" or "allow to_sym on interpolated strings", exact naming TBD, to give users the choice of which style to use.

Additional Context

To reiterate, this is based on the assumption that :"#{thing}" is equivalent to "#{thing}".to_sym in terms of the construction of a string before converting it to a symbol. I am happy to be shown I am wrong on this but I did not see any proofs or justifications in the original PR that introduced Lint/SymbolConversion nor the PR that introduced the string interpolation case.

RossBarnie avatar Jun 04 '24 10:06 RossBarnie