Class: RuboCop::Cop::Rails::Validation

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

Overview

Checks for the use of old-style attribute validation macros.

Examples:

# bad
validates_acceptance_of :foo
validates_comparison_of :foo
validates_confirmation_of :foo
validates_exclusion_of :foo
validates_format_of :foo
validates_inclusion_of :foo
validates_length_of :foo
validates_numericality_of :foo
validates_presence_of :foo
validates_absence_of :foo
validates_size_of :foo
validates_uniqueness_of :foo

# good
validates :foo, acceptance: true
validates :foo, confirmation: true
validates :foo, comparison: true
validates :foo, exclusion: true
validates :foo, format: true
validates :foo, inclusion: true
validates :foo, length: true
validates :foo, numericality: true
validates :foo, presence: true
validates :foo, absence: true
validates :foo, length: true
validates :foo, uniqueness: true

Constant Summary collapse

MSG =
'Prefer the new style validations `%<prefer>s` over `%<current>s`.'
TYPES =
%w[
  acceptance
  comparison
  confirmation
  exclusion
  format
  inclusion
  length
  numericality
  presence
  absence
  size
  uniqueness
].freeze
RESTRICT_ON_SEND =
TYPES.map { |p| :"validates_#{p}_of" }.freeze
ALLOWLIST =
TYPES.map { |p| "validates :column, #{p}: value" }.freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rubocop/cop/rails/validation.rb', line 60

def on_send(node)
  return if node.receiver
  return unless (last_argument = node.last_argument)

  range = node.loc.selector

  add_offense(range, message: message(node)) do |corrector|
    return if !last_argument.literal? && !last_argument.splat_type? && !frozen_array_argument?(last_argument)

    corrector.replace(range, 'validates')
    correct_validate_type(corrector, node)
  end
end