Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect unnecessary stringify_keys/symbolize_keys calls #1332

Open
fatkodima opened this issue Aug 16, 2024 · 3 comments · May be fixed by #1333
Open

Detect unnecessary stringify_keys/symbolize_keys calls #1332

fatkodima opened this issue Aug 16, 2024 · 3 comments · May be fixed by #1333

Comments

@fatkodima
Copy link
Contributor

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
Copy link
Contributor

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
Copy link
Contributor

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 fatkodima linked a pull request Aug 18, 2024 that will close this issue
@fatkodima
Copy link
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants