Sha256: 6ad922cc7618fb0e898146d1ce4abb2642ae0b43a212267024de5942609216c8

Contents?: true

Size: 1.39 KB

Versions: 13

Compression:

Stored size: 1.39 KB

Contents

# encoding: utf-8
# 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 = Parser::Source::Range.new(node_expr.source_buffer,
                                               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
fluent-plugin-detect-memb-exceptions-0.0.2 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/style/attr.rb
fluent-plugin-detect-memb-exceptions-0.0.1 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/style/attr.rb
rubocop-0.42.0 lib/rubocop/cop/style/attr.rb
rubocop-0.41.2 lib/rubocop/cop/style/attr.rb
rubocop-0.41.1 lib/rubocop/cop/style/attr.rb
rubocop-0.41.0 lib/rubocop/cop/style/attr.rb
rubocop-0.40.0 lib/rubocop/cop/style/attr.rb
rubocop-0.39.0 lib/rubocop/cop/style/attr.rb
rubocop-0.38.0 lib/rubocop/cop/style/attr.rb
rubocop-0.37.2 lib/rubocop/cop/style/attr.rb
rubocop-0.37.1 lib/rubocop/cop/style/attr.rb
rubocop-0.37.0 lib/rubocop/cop/style/attr.rb
rubocop-0.36.0 lib/rubocop/cop/style/attr.rb