rubocop / rubocop-rails

A RuboCop extension focused on enforcing Rails best practices and coding conventions.
https://docs.rubocop.org/rubocop-rails
MIT License
802 stars 257 forks source link

Detect unnecessary `stringify_keys`/`symbolize_keys` calls #1332

Open fatkodima opened 1 month ago

fatkodima commented 1 month ago

In our app, I noticed a lot of unnecessary usage of the mentioned methods when we can just rewrite the hash definition (or the hash is already having the right format, so method call is not needed).

# bad
SomeJob.perform_async({ foo: 1, bar: 2 }.stringify_keys)

# good
SomeJob.perform_async({ "foo" => 1, "bar" => 2 })

I was also able to find a few offences in OSS projects, for example gitlab.

1 offense for symbolize_keys https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/instrumentation/redis_payload.rb#L22-29

and 54 offenses for stringify_keyslike https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/lfs_download_object.rb#L23-28

Earlopain commented 4 weeks ago

Basically, these would be offenses if I understand you:

{ foo: 1, "bar" => 2 }.stringify_keys
# => all keys are known, just stringify yourself
{ foo: 1, "bar" => 2 }.symbolize_keys
# => and the same, in the opposite direction

Principally I agree. I can especially see how someone would add symbolize_keys to that one example you linked since the keys to look rather string-like.

vlad-pisanov commented 4 weeks ago

This could also be extended to handle symbolize_keys! and even deep_symbolize_keys/deep_symbolize_keys! if all nested values are literals.

# bad
{ "foo" => { bar: 1 } }.symbolize_keys
{ foo: { bar: 1 } }.symbolize_keys
{ foo: { bar: 1 } }.symbolize_keys!
{ "foo" => { "bar" => 1 } }.deep_symbolize_keys
{ foo: { bar: 1 } }.deep_symbolize_keys
{ foo: { bar: 1 } }.deep_symbolize_keys!

# good
{ foo: { bar: 1 } }
fatkodima commented 4 weeks ago

Opened a PR. Actually, found 57 offenses in my app.