Sha256: b5971b0749cff422b82f209699448a661cf1e88a8f2fe43bf6de05b9a09909bd

Contents?: true

Size: 1.81 KB

Versions: 14

Compression:

Stored size: 1.81 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Sort RSpec metadata alphabetically.
      #
      # @example
      #   # bad
      #   describe 'Something', :b, :a
      #   context 'Something', foo: 'bar', baz: true
      #   it 'works', :b, :a, foo: 'bar', baz: true
      #
      #   # good
      #   describe 'Something', :a, :b
      #   context 'Something', baz: true, foo: 'bar'
      #   it 'works', :a, :b, baz: true, foo: 'bar'
      #
      class SortMetadata < Base
        extend AutoCorrector
        include Metadata
        include RangeHelp

        MSG = 'Sort metadata alphabetically.'

        def on_metadata(symbols, hash)
          pairs = hash&.pairs || []
          return if sorted?(symbols, pairs)

          crime_scene = crime_scene(symbols, pairs)
          add_offense(crime_scene) do |corrector|
            corrector.replace(crime_scene, replacement(symbols, pairs))
          end
        end

        private

        def crime_scene(symbols, pairs)
          metadata = symbols + pairs

          range_between(
            metadata.first.source_range.begin_pos,
            metadata.last.source_range.end_pos
          )
        end

        def replacement(symbols, pairs)
          (sort_symbols(symbols) + sort_pairs(pairs)).map(&:source).join(', ')
        end

        def sorted?(symbols, pairs)
          symbols == sort_symbols(symbols) && pairs == sort_pairs(pairs)
        end

        def sort_pairs(pairs)
          pairs.sort_by { |pair| pair.key.source.downcase }
        end

        def sort_symbols(symbols)
          symbols.sort_by do |symbol|
            if %i[str sym].include?(symbol.type)
              symbol.value.to_s.downcase
            else
              symbol.source.downcase
            end
          end
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
rubocop-rspec-2.31.0 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.30.0 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.29.2 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.29.1 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.29.0 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.28.0 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.27.1 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.27.0 lib/rubocop/cop/rspec/sort_metadata.rb
mlh-rubocop-config-1.0.3 vendor/bundle/ruby/3.2.0/gems/rubocop-rspec-2.26.1/lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.26.1 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.26.0 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.25.0 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.24.1 lib/rubocop/cop/rspec/sort_metadata.rb
rubocop-rspec-2.24.0 lib/rubocop/cop/rspec/sort_metadata.rb