Class: RuboCop::Cop::Sevencop::RailsUniquenessValidatorExplicitCaseSensitivity

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/sevencop/rails_uniqueness_validator_explicit_case_sensitivity.rb

Overview

Identifies use of UniquenessValidator without :case_sensitive option. Useful to keep the same behavior between Rails 6.0 and 6.1 where case insensitive collation is used in MySQL.

Examples:


# bad
validates :name, uniqueness: true

# good
validates :name, uniqueness: { case_sensitive: true }

# good
validates :name, uniqueness: { case_sensitive: false }

# bad
validates :name, uniqueness: { allow_nil: true, scope: :user_id }

# good
validates :name, uniqueness: { allow_nil: true, scope: :user_id, case_sensitive: true }

Cop Safety Information:

  • This cop is unsafe because it can register a false positive.

Constant Summary collapse

MSG =
'Specify :case_sensitivity option on use of UniquenessValidator.'
RESTRICT_ON_SEND =
%i[validates].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object

Parameters:

  • node (RuboCop::AST::SendNode)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rubocop/cop/sevencop/rails_uniqueness_validator_explicit_case_sensitivity.rb', line 37

def on_send(node)
  return unless validates_uniqueness?(node) && !validates_uniqueness_with_case_sensitivity?(node)

  uniqueness_value = find_uniqueness_value(node)
  add_offense(uniqueness_value) do |corrector|
    if uniqueness_value.true_type?
      corrector.replace(
        uniqueness_value,
        '{ case_sensitive: true }'
      )
    else
      corrector.insert_after(
        uniqueness_value.pairs.last,
        ', case_sensitive: true'
      )
    end
  end
end