Sha256: 4fac628f24528cbee62407cc04a74f5475de7a7592127d5b9d7a14022780b6dc

Contents?: true

Size: 1.19 KB

Versions: 11

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop checks for add_column call with NOT NULL constraint
      # in migration file.
      #
      # @example
      #   # bad
      #   add_column :users, :name, :string, null: false
      #
      #   # good
      #   add_column :users, :name, :string, null: true
      #   add_column :users, :name, :string, null: false, default: ''
      class NotNullColumn < Cop
        MSG = 'Do not add a NOT NULL column without a default value.'.freeze

        def_node_matcher :add_not_null_column?, <<-PATTERN
          (send nil :add_column _ _ _ (hash $...))
        PATTERN

        def_node_matcher :null_false?, <<-PATTERN
          (pair (sym :null) (false))
        PATTERN

        def_node_matcher :has_default?, <<-PATTERN
          (pair (sym :default) !(:nil))
        PATTERN

        def on_send(node)
          pairs = add_not_null_column?(node)
          return unless pairs
          return if pairs.any? { |pair| has_default?(pair) }

          null_false = pairs.find { |pair| null_false?(pair) }
          return unless null_false

          add_offense(null_false, :expression)
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

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