Sha256: e3eb4bd918d3c357d7620409c7f89c726b7560c792cadaea24b9caf37be377ee

Contents?: true

Size: 1.23 KB

Versions: 33

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for cases when you could use a block
      # accepting version of a method that does automatic
      # resource cleanup.
      #
      # @example
      #
      #   # bad
      #   f = File.open('file')
      #
      #   # good
      #   File.open('file') do |f|
      #     # ...
      #   end
      class AutoResourceCleanup < Base
        MSG = 'Use the block version of `%<class>s.%<method>s`.'

        TARGET_METHODS = {
          File: :open
        }.freeze

        RESTRICT_ON_SEND = TARGET_METHODS.values.freeze

        def on_send(node)
          TARGET_METHODS.each do |target_class, target_method|
            next if node.method_name != target_method

            target_receiver = s(:const, nil, target_class)
            next if node.receiver != target_receiver

            next if cleanup?(node)

            add_offense(node, message: format(MSG, class: target_class, method: target_method))
          end
        end

        private

        def cleanup?(node)
          parent = node.parent
          node.block_argument? ||
            (parent && (parent.block_type? || !parent.lvasgn_type?))
        end
      end
    end
  end
end

Version data entries

33 entries across 33 versions & 2 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/auto_resource_cleanup.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/auto_resource_cleanup.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/auto_resource_cleanup.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/auto_resource_cleanup.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/auto_resource_cleanup.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.12.1 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.12.0 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.11.0 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.10.0 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.9.1 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.9.0 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.8.1 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.8.0 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.7.0 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.6.1 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.6.0 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.5.2 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.5.1 lib/rubocop/cop/style/auto_resource_cleanup.rb
rubocop-1.5.0 lib/rubocop/cop/style/auto_resource_cleanup.rb