Class: RuboCop::Cop::Rails::RedundantAllowNil

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rails/redundant_allow_nil.rb

Overview

Checks Rails model validations for a redundant ‘allow_nil` when `allow_blank` is present.

Examples:

# bad
validates :x, length: { is: 5 }, allow_nil: true, allow_blank: true

# bad
validates :x, length: { is: 5 }, allow_nil: false, allow_blank: true

# bad
validates :x, length: { is: 5 }, allow_nil: false, allow_blank: false

# good
validates :x, length: { is: 5 }, allow_blank: true

# good
validates :x, length: { is: 5 }, allow_blank: false

# good
# Here, `nil` is valid but `''` is not
validates :x, length: { is: 5 }, allow_nil: true, allow_blank: false

Constant Summary collapse

MSG_SAME =
'`allow_nil` is redundant when `allow_blank` has the same value.'
MSG_ALLOW_NIL_FALSE =
'`allow_nil: false` is redundant when `allow_blank` is true.'
RESTRICT_ON_SEND =
%i[validates].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/rails/redundant_allow_nil.rb', line 39

def on_send(node)
  allow_nil, allow_blank = find_allow_nil_and_allow_blank(node)
  return unless allow_nil && allow_blank

  allow_nil_val = allow_nil.children.last
  allow_blank_val = allow_blank.children.last

  if allow_nil_val.type == allow_blank_val.type
    register_offense(allow_nil, MSG_SAME)
  elsif allow_nil_val.false_type? && allow_blank_val.true_type?
    register_offense(allow_nil, MSG_ALLOW_NIL_FALSE)
  end
end