Sha256: f2e3aefa75483127a2c8357821911a0ecea8f367fd817ddf86329aad89bd5e4f

Contents?: true

Size: 1.82 KB

Versions: 6

Compression:

Stored size: 1.82 KB

Contents

# frozen_string_literal: true

module RuboCop
  module AST
    # A node extension for `case` nodes. This will be used in place of a plain
    # node when the builder constructs the AST, making its methods available
    # to all `case` nodes within RuboCop.
    class CaseNode < Node
      include ConditionalNode

      # Returns the keyword of the `case` statement as a string.
      #
      # @return [String] the keyword of the `case` statement
      def keyword
        'case'
      end

      # Calls the given block for each `when` node in the `case` statement.
      # If no block is given, an `Enumerator` is returned.
      #
      # @return [self] if a block is given
      # @return [Enumerator] if no block is given
      def each_when
        return when_branches.to_enum(__method__) unless block_given?

        when_branches.each do |condition|
          yield condition
        end

        self
      end

      # Returns an array of all the when branches in the `case` statement.
      #
      # @return [Array<WhenNode>] an array of `when` nodes
      def when_branches
        node_parts[1...-1]
      end

      # Returns the else branch of the `case` statement, if any.
      #
      # @return [Node] the else branch node of the `case` statement
      # @return [nil] if the case statement does not have an else branch.
      def else_branch
        node_parts[-1]
      end

      # Checks whether this case statement has an `else` branch.
      #
      # @return [Boolean] whether the `case` statement has an `else` branch
      def else?
        loc.else
      end

      # Custom destructuring method. This can be used to normalize
      # destructuring for different variations of the node.
      #
      # @return [Array<Node>] the different parts of the `case` statement
      def node_parts
        to_a
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-0.52.1 lib/rubocop/ast/node/case_node.rb
rubocop-0.52.0 lib/rubocop/ast/node/case_node.rb
rubocop-0.51.0 lib/rubocop/ast/node/case_node.rb
rubocop-0.50.0 lib/rubocop/ast/node/case_node.rb
rubocop-0.49.1 lib/rubocop/ast/node/case_node.rb
rubocop-0.49.0 lib/rubocop/ast/node/case_node.rb