Sha256: 97319c35d3bfbb40c5814903aef962004d59b940a850f59122d16adb5108fd17

Contents?: true

Size: 1.31 KB

Versions: 7

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 |attribute|
            value = attribute.children.last

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

        def autocorrect(node)
          expression = default_attribute(node).children.last

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

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rubocop-infinum-0.5.1 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.5.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.4.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.3.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.2.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.1.1 lib/rubocop/cop/infinum/attribute_default_block_value.rb
rubocop-infinum-0.1.0 lib/rubocop/cop/infinum/attribute_default_block_value.rb