Add cop Style/HashTransformation
gitlab-styles so all GitLab projects can benefit from it.
Description of the proposal
This MR adds a new Style/HashTransformation to promote the block flavour of #to_h.
It's basically, .to_h { ... } instead of map { ... }.to_h.
Note, some cases are already covered by other cops Style/HashTransformKeys and Style/HashTransformedValues which are already enabled at GitLab.
This MR is heavily based on https://github.com/eugeneius/rubocop-performance/blob/hash_transformation/lib/rubocop/cop/performance/hash_transformation.rb. Kudos to Eugene Kenny
The end goal is to upstream this cop to https://github.com/rubocop-hq/rubocop as Style/HashTransformation (
Refs gitlab-org/gitlab#220003 (closed)
Examples
# bad
hash.collect { |k, v| [v, k] }.to_h
Hash[hash.map { |k, v| [v, k] }]
# good
hash.to_h { |k, v| [v, k] }
Offense
app/controllers/projects/branches_controller.rb:52:33: C: [Corrected] Gitlab/HashTransformation: Use to_h { ... } instead of map { ... }.to_h.
render json: branches.map { |branch| [branch.name, service.call(branch)] }.to_h
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
app/finders/ci/commit_statuses_finder.rb:24:14: C: [Corrected] Gitlab/HashTransformation: Use to_h { ... } instead of map { ... }.to_h.
refs.map do |ref| ...
^^^^^^^^^^^^
See gitlab-org/gitlab!54687 (closed) for the full diff.
Check-list
- [-] Make sure this MR enables a static analysis check rule for new usage but
ignores current offenses
- Will be done after upgrading
gitlab-styles
- Will be done after upgrading
-
Mention this proposal in the relevant Slack channels (e.g. #development,#backend,#frontend) - [-] If there is a choice to make between two potential styles, set up an emoji vote in the MR:
- CHOICE_A:
🅰 - CHOICE_B:
🅱 - Vote yourself for both choices so that people know these are the choices
- CHOICE_A:
-
The MR doesn't have significant objections, and is getting a majority of 👍 vs👎 (remember that we don't need to reach a consensus) - [-] (If applicable) One style is getting a majority of vote (compared to the other choice)
- [-] (If applicable) Update the MR with the chosen style
-
Follow the review process as usual -
Upgrade gitlab-styleswhich introduces the cop in dependent projects-
Make sure this MR enables a static analysis check rule for new usage but ignores current offenses -
Create a follow-up issue on the dependent project to fix the current offenses as a separate iteration: gitlab-org/gitlab#322739 (closed) -
(When added to gitlab-org/gitlab) Mention it again:-
In the relevant Slack channels (e.g. #development,#backend,#frontend) -
(Optional depending on the impact of the change) In the Engineering Week in Review
-
-