Class: RuboCop::Cop::Ipepe::AlphabeticalHashKeys
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Ipepe::AlphabeticalHashKeys
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/ipepe/alphabetical_hash_keys.rb
Constant Summary collapse
- MSG =
"Ensure that keys in hash are in alphabetical order".freeze
Instance Method Summary collapse
-
#on_hash(node) ⇒ Object
rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity.
Instance Method Details
#on_hash(node) ⇒ Object
rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/rubocop/cop/ipepe/alphabetical_hash_keys.rb', line 8 def on_hash(node) # rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity keys = node.children.select(&:pair_type?).map(&:key) sorted_keys = keys.sort_by do |k| if k.respond_to?(:value) k.value.to_s elsif k.respond_to?(:const_name) k.const_name.to_s end end return if cop_not_applicable?(keys, sorted_keys) add_offense(node) do |corrector| join_keys_with = " " join_keys_with = "\n " if node.source.include?("\n") corrector.replace( node, [ ("{" if node.source.start_with?("{")), sorted_keypairs(node, sorted_keys).join(",#{join_keys_with}"), ("}" if node.source.end_with?("}")) ].compact.join(join_keys_with) ) end end |