Sha256: a01b43c5f6855758709c0af6d5e1ae305101f07037f30ea466ffe4c812d5c865

Contents?: true

Size: 1.87 KB

Versions: 8

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop checks for the use of output calls like puts and print
      #
      # @safety
      #   This cop's autocorrection is unsafe because depending on the Rails log level configuration,
      #   changing from `puts` to `Rails.logger.debug` could result in no output being shown.
      #
      # @example
      #   # bad
      #   puts 'A debug message'
      #   pp 'A debug message'
      #   print 'A debug message'
      #
      #   # good
      #   Rails.logger.debug 'A debug message'
      class Output < Base
        include RangeHelp
        extend AutoCorrector

        MSG = 'Do not write to stdout. ' \
              "Use Rails's logger if you want to log."
        RESTRICT_ON_SEND = %i[
          ap p pp pretty_print print puts binwrite syswrite write write_nonblock
        ].freeze

        def_node_matcher :output?, <<~PATTERN
          (send nil? {:ap :p :pp :pretty_print :print :puts} ...)
        PATTERN

        def_node_matcher :io_output?, <<~PATTERN
          (send
            {
              (gvar #match_gvar?)
              {(const nil? :STDOUT) (const nil? :STDERR)}
            }
            {:binwrite :syswrite :write :write_nonblock}
            ...)
        PATTERN

        def on_send(node)
          return unless (output?(node) || io_output?(node)) && node.arguments?

          range = offense_range(node)

          add_offense(range) do |corrector|
            corrector.replace(range, 'Rails.logger.debug')
          end
        end

        private

        def match_gvar?(sym)
          %i[$stdout $stderr].include?(sym)
        end

        def offense_range(node)
          if node.receiver
            range_between(node.loc.expression.begin_pos, node.loc.selector.end_pos)
          else
            node.loc.selector
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-rails-2.14.2/lib/rubocop/cop/rails/output.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-rails-2.14.2/lib/rubocop/cop/rails/output.rb
rubocop-rails-2.14.2 lib/rubocop/cop/rails/output.rb
rubocop-rails-2.14.1 lib/rubocop/cop/rails/output.rb
rubocop-rails-2.14.0 lib/rubocop/cop/rails/output.rb
rubocop-rails-2.13.2 lib/rubocop/cop/rails/output.rb
rubocop-rails-2.13.1 lib/rubocop/cop/rails/output.rb
rubocop-rails-2.13.0 lib/rubocop/cop/rails/output.rb