Class: RuboCop::Cop::YiffSpace::BelongsToUserMissingIp

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ActiveRecordHelper, NodeFormattingHelper
Defined in:
lib/rubocop/cop/yiff_space/belongs_to_user_missing_ip.rb

Overview

Detects when a ‘belongs_to_user` call is missing `ip: true` even though a corresponding `<attr>_ip_addr` column exists in the database schema. It auto-corrects by adding `ip: true`.

Examples:

# bad - `creator_ip_addr` column exists but `ip:` is not specified
belongs_to_user(:creator)

# bad - `ip: false` explicitly opts out but the column exists
belongs_to_user(:creator, ip: false)

# good
belongs_to_user(:creator, ip: true)

# good - no `creator_ip_addr` column exists in the schema
belongs_to_user(:creator)

Constant Summary collapse

MSG =
"Specify `ip: true` when a `belongs_to_user(%<attr>s)` relation has a corresponding `%<ip_attr>s` column"

Constants included from NodeFormattingHelper

NodeFormattingHelper::BASIC

Instance Method Summary collapse

Methods included from NodeFormattingHelper

#format_node

Instance Method Details

#belongs_to_user?(node) ⇒ Object



37
38
39
# File 'lib/rubocop/cop/yiff_space/belongs_to_user_missing_ip.rb', line 37

def_node_matcher(:belongs_to_user?, <<~PATTERN)
  (send nil? :belongs_to_user $_ $...)
PATTERN

#on_csend(node) ⇒ Object



65
66
67
# File 'lib/rubocop/cop/yiff_space/belongs_to_user_missing_ip.rb', line 65

def on_csend(node)
  on_send(node)
end

#on_send(node) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rubocop/cop/yiff_space/belongs_to_user_missing_ip.rb', line 41

def on_send(node)
  belongs_to_user?(node) do |receiver, code|
    return unless receiver.type?(:str, :sym)

    attr = format_node(receiver)
    return if attr.nil? || attr.empty?

    options = format_node(code.last, {})
    return unless [nil, "", false].include?(options[:ip])

    return unless schema

    table = table(node)
    return unless table

    column = "#{attr}_ip_addr"
    exists = table.with_column?(name: column)

    return unless exists

    register_offense(node, attr, options, column)
  end
end