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

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/rails/validation.rb

Overview

This cop checks for the use of old-style attribute validation macros.

Examples:

# bad
validates_acceptance_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, 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, size: true
validates :foo, uniqueness: true

Constant Summary collapse

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

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



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

def autocorrect(node)
  last_argument = node.arguments.last
  return if !last_argument.literal? && !last_argument.splat_type? &&
            !frozen_array_argument?(last_argument)

  lambda do |corrector|
    corrector.replace(node.loc.selector, 'validates')
    correct_validate_type(corrector, node)
  end
end

#on_send(node) ⇒ Object



56
57
58
59
60
# File 'lib/rubocop/cop/rails/validation.rb', line 56

def on_send(node)
  return unless !node.receiver && DENYLIST.include?(node.method_name)

  add_offense(node, location: :selector)
end