Sha256: 83741bed3c6e369a9563d9d0ca78190a6ffebc3d3dab1c73f7a3b48a4624da53

Contents?: true

Size: 1.31 KB

Versions: 4

Compression:

Stored size: 1.31 KB

Contents

# frozen_string_literal: true

require 'rubocop'

module RuboCop
  module Cop
    module Infinum
      # This cop looks for `attribute` class methods that specify a `:default` option
      # and pass it a method without a block.
      #
      # @example
      #   # bad
      #   class User < ApplicationRecord
      #     attribute :confirmed_at, :datetime, default: Time.zone.now
      #   end
      #
      #   # good
      #   class User < ActiveRecord::Base
      #     attribute :confirmed_at, :datetime, default: -> { Time.zone.now }
      #   end
      class AttributeDefaultBlockValue < ::RuboCop::Cop::Cop
        MSG = 'Pass method in a block to `:default` option.'

        def_node_matcher :default_attribute, <<~PATTERN
          (send nil? :attribute _ ?_ (hash <$#attribute ...>))
        PATTERN

        def_node_matcher :attribute, '(pair (sym :default) $_)'

        def on_send(node)
          default_attribute(node) do |hash_pair|
            value = attribute(hash_pair)

            add_offense(node, location: value) if value.send_type?
          end
        end

        def autocorrect(node)
          expression = attribute(default_attribute(node))

          lambda do |corrector|
            corrector.replace(expression, "-> { #{expression.source} }")
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-infinum-0.9.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.8.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.7.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.6.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb