summaryrefslogtreecommitdiff
path: root/rubocop/cop/avoid_break_from_strong_memoize.rb
blob: 9b436118db3e7a1e6862fad93e68e9bffdc64f9a (plain)
1
2
3
4
5
6
7
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true

module RuboCop
  module Cop
    # Checks for break inside strong_memoize blocks.
    # For more information see: https://gitlab.com/gitlab-org/gitlab-ce/issues/42889
    #
    # @example
    #   # bad
    #   strong_memoize(:result) do
    #     break if something
    #
    #     do_an_heavy_calculation
    #   end
    #
    #   # good
    #   strong_memoize(:result) do
    #     next if something
    #
    #     do_an_heavy_calculation
    #   end
    #
    class AvoidBreakFromStrongMemoize < RuboCop::Cop::Cop
      MSG = 'Do not use break inside strong_memoize, use next instead.'

      def on_block(node)
        block_body = node.body

        return unless block_body
        return unless node.method_name == :strong_memoize

        block_body.each_node(:break) do |break_node|
          next if container_block_for(break_node) != node

          add_offense(break_node)
        end
      end

      private

      def container_block_for(current_node)
        current_node = current_node.parent until current_node.type == :block && current_node.method_name == :strong_memoize

        current_node
      end
    end
  end
end