rubocop/rubocop-rails

Detect unnecessary `stringify_keys`/`symbolize_keys` calls

Opened this issue · 3 comments

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

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.

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 } }

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