Class: RuboCop::Cop::Rails::ThreeStateBooleanColumn

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/three_state_boolean_column.rb

Overview

Enforces that boolean columns are created with default values (‘false` or `true`) and `NOT NULL` constraint.

Examples:

# bad
add_column :users, :active, :boolean
t.column :active, :boolean
t.boolean :active

# good
add_column :users, :active, :boolean, default: true, null: false
t.column :active, :boolean, default: true, null: false
t.boolean :active, default: true, null: false

Constant Summary collapse

MSG =
'Boolean columns should always have a default value and a `NOT NULL` constraint.'
RESTRICT_ON_SEND =
%i[add_column column boolean].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rubocop/cop/rails/three_state_boolean_column.rb', line 41

def on_send(node)
  three_state_boolean?(node) do |column_node, options_node|
    options_node = options_node.first

    return if required_options?(options_node)

    def_node = node.each_ancestor(:def, :defs).first
    table_node = table_node(node)
    return if def_node && (table_node.nil? || change_column_null?(def_node, table_node, column_node))

    add_offense(node)
  end
end