Add RuboCop Gitlab/HashTransformation
Description of the proposal
This MR adds a new Gitlab/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 #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 !53486 (9ff009d0) for the full diff.
.rubocop_manual_todo.yml
(see checkbox below).
Check-list
-
Make sure this MR enables a static analysis check rule for new usage but ignores current offenses -
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 -
Create a follow-up issue to fix the current offenses as a separate iteration: ISSUE_LINK -
Follow the review process as usual -
Once approved and merged by a maintainer, 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
-
Edited by Peter Leitzen