Sha256: d229bbf1124b22c30930e10670d02d41e40bd06dc5780a59840a45d6338124fb

Contents?: true

Size: 1.28 KB

Versions: 12

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop identifies places where `$stderr.puts` can be replaced by
      # `warn`. The latter has the advantage of easily being disabled by,
      # the `-W0` interpreter flag or setting `$VERBOSE` to `nil`.
      #
      # @example
      #   # bad
      #   $stderr.puts('hello')
      #
      #   # good
      #   warn('hello')
      #
      class StderrPuts < Cop
        include RangeHelp

        MSG = 'Use `warn` instead of `$stderr.puts` to allow such output ' \
              'to be disabled.'.freeze

        def_node_matcher :stderr_puts?, <<-PATTERN
          (send
            (gvar #stderr_gvar?) :puts
            ...)
        PATTERN

        def on_send(node)
          return unless stderr_puts?(node)

          add_offense(node, location: stderr_puts_range(node))
        end

        def autocorrect(node)
          lambda do |corrector|
            corrector.replace(stderr_puts_range(node), 'warn')
          end
        end

        private

        def stderr_gvar?(sym)
          sym == :$stderr
        end

        def stderr_puts_range(send)
          range_between(
            send.loc.expression.begin_pos,
            send.loc.selector.end_pos
          )
        end
      end
    end
  end
end

Version data entries

12 entries across 10 versions & 2 rubygems

Version Path
rubocop-0.65.0 lib/rubocop/cop/style/stderr_puts.rb
rubocop-0.64.0 lib/rubocop/cop/style/stderr_puts.rb
rubocop-0.63.1 lib/rubocop/cop/style/stderr_puts.rb
rubocop-0.63.0 lib/rubocop/cop/style/stderr_puts.rb
rubocop-0.62.0 lib/rubocop/cop/style/stderr_puts.rb
rubocop-0.61.1 lib/rubocop/cop/style/stderr_puts.rb
rubocop-0.61.0 lib/rubocop/cop/style/stderr_puts.rb
config_gems_initialization_aim-0.1.4 vendor/bundle/ruby/2.5.0/gems/rubocop-0.60.0/lib/rubocop/cop/style/stderr_puts.rb
config_gems_initialization_aim-0.1.4 vendor/bundle/ruby/2.5.0/gems/config_gems_initialization_aim-0.1.1/vendor/bundle/ruby/2.5.0/gems/rubocop-0.60.0/lib/rubocop/cop/style/stderr_puts.rb
config_gems_initialization_aim-0.1.3 vendor/bundle/ruby/2.5.0/gems/rubocop-0.60.0/lib/rubocop/cop/style/stderr_puts.rb
config_gems_initialization_aim-0.1.3 vendor/bundle/ruby/2.5.0/gems/config_gems_initialization_aim-0.1.1/vendor/bundle/ruby/2.5.0/gems/rubocop-0.60.0/lib/rubocop/cop/style/stderr_puts.rb
rubocop-0.60.0 lib/rubocop/cop/style/stderr_puts.rb