Sha256: 661a9b9a9694d068f7a32da4b86b1388255ed55b124ebc50b3efc656adc320fa

Contents?: true

Size: 1.56 KB

Versions: 4

Compression:

Stored size: 1.56 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks expressions wrapping styles for multiline memoization.
      #
      # @example
      #
      #   # EnforcedStyle: keyword (default)
      #
      #   @bad
      #   foo ||= (
      #     bar
      #     baz
      #   )
      #
      #   @good
      #   foo ||= begin
      #     bar
      #     baz
      #   end
      #
      # @example
      #
      #   # EnforcedStyle: braces
      #
      #   @bad
      #   foo ||= begin
      #     bar
      #     baz
      #   end
      #
      #   @good
      #   foo ||= (
      #     bar
      #     baz
      #   )
      class MultilineMemoization < Cop
        include ConfigurableEnforcedStyle

        MSG = 'Wrap multiline memoization blocks in `begin` and `end`.'.freeze

        def on_or_asgn(node)
          _lhs, rhs = *node

          return unless bad_rhs?(rhs)

          add_offense(rhs, node.source_range, MSG)
        end

        private

        def autocorrect(node)
          lambda do |corrector|
            if style == :keyword
              corrector.replace(node.loc.begin, 'begin')
              corrector.replace(node.loc.end, 'end')
            else
              corrector.replace(node.loc.begin, '(')
              corrector.replace(node.loc.end, ')')
            end
          end
        end

        def bad_rhs?(rhs)
          return false unless rhs.multiline?
          if style == :keyword
            rhs.begin_type?
          else
            rhs.kwbegin_type?
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-0.49.1 lib/rubocop/cop/style/multiline_memoization.rb
rubocop-0.49.0 lib/rubocop/cop/style/multiline_memoization.rb
rubocop-0.48.1 lib/rubocop/cop/style/multiline_memoization.rb
rubocop-0.48.0 lib/rubocop/cop/style/multiline_memoization.rb