Sha256: c414dffe4905c5f7be6136dd45cc7974ed4b63d9bcbea64561a48746e8a93029

Contents?: true

Size: 1.53 KB

Versions: 14

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks uses of the `then` keyword
      # in multi-line when statements.
      #
      # @example
      #   # bad
      #   case foo
      #   when bar then
      #   end
      #
      #   # good
      #   case foo
      #   when bar
      #   end
      #
      #   # good
      #   case foo
      #   when bar then do_something
      #   end
      #
      #   # good
      #   case foo
      #   when bar then do_something(arg1,
      #                              arg2)
      #   end
      #
      class MultilineWhenThen < Base
        include RangeHelp
        extend AutoCorrector

        MSG = 'Do not use `then` for multiline `when` statement.'

        def on_when(node)
          return if !node.then? || require_then?(node)

          range = node.loc.begin
          add_offense(range) do |corrector|
            corrector.remove(
              range_with_surrounding_space(range: range, side: :left, newlines: false)
            )
          end
        end

        private

        # Requires `then` for write `when` and its body on the same line.
        def require_then?(when_node)
          unless when_node.conditions.first.first_line == when_node.conditions.last.last_line
            return true
          end
          return false unless when_node.body

          when_node.loc.line == when_node.body.loc.line
        end

        def accept_node_type?(node)
          node&.array_type? || node&.hash_type?
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
rubocop-1.22.1 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.22.0 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.21.0 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.20.0 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.19.1 lib/rubocop/cop/style/multiline_when_then.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/rubocop-1.18.3/lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.19.0 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.18.4 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.18.3 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.18.2 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.18.1 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.18.0 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.17.0 lib/rubocop/cop/style/multiline_when_then.rb
rubocop-1.16.1 lib/rubocop/cop/style/multiline_when_then.rb