Sha256: ad19e6634333d71d40c73f6d49ecb0612f89c82aa2857685f07fe4e51d934e51

Contents?: true

Size: 1.25 KB

Versions: 13

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for uses of Module#attr.
      class Attr < Cop
        def on_send(node)
          return unless node.command?(:attr)
          _receiver, _method_name, *args = *node
          msg = "Do not use `attr`. Use `#{replacement_method(node)}` instead."

          add_offense(node, :selector, msg) if args.any?
        end

        def autocorrect(node)
          _receiver, _method_name, attr_name, setter = *node
          node_expr = node.source_range
          attr_expr = attr_name.source_range

          if setter && (setter.true_type? || setter.false_type?)
            remove = range_between(attr_expr.end_pos, node_expr.end_pos)
          end

          lambda do |corrector|
            corrector.replace(node.loc.selector, replacement_method(node))
            corrector.replace(remove, '') if remove
          end
        end

        private

        def replacement_method(node)
          _receiver, _method_name, _attr_name, setter = *node
          if setter && (setter.true_type? || setter.false_type?)
            setter.true_type? ? 'attr_accessor' : 'attr_reader'
          else
            'attr_reader'
          end
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/attr.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/attr.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/attr.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/attr.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/attr.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/attr.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/attr.rb
rubocop-0.47.1 lib/rubocop/cop/style/attr.rb
rubocop-0.47.0 lib/rubocop/cop/style/attr.rb
rubocop-0.46.0 lib/rubocop/cop/style/attr.rb
rubocop-0.45.0 lib/rubocop/cop/style/attr.rb
rubocop-0.44.1 lib/rubocop/cop/style/attr.rb
rubocop-0.44.0 lib/rubocop/cop/style/attr.rb