Class: RuboCop::Cop::YiffSpace::BelongsToUserInvalidIp

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

Overview

Detects when ‘ip:` is specified in a `belongs_to_user` call but the corresponding IP address column does not exist in the database schema. It auto-corrects by removing the invalid `ip:` option.

Examples:

# bad - no `creator_ip_addr` column exists in the schema
belongs_to_user(:creator, ip: true)

# bad - no `creator_custom` column exists in the schema
belongs_to_user(:creator, ip: "creator_custom")

# good
belongs_to_user(:creator)

# good - `creator_ip_addr` column exists in the schema
belongs_to_user(:creator, ip: true)

Constant Summary collapse

MSG =
"`ip: %<ip_set>s` set for `belongs_to_user(%<attr>s)` when `%<ip_attr>s` column does not exist"

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_invalid_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_invalid_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_invalid_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 if [nil, "", false].include?(options[:ip])

    return unless schema

    table = table(node)
    return unless table

    column = options[:ip] == true ? "#{attr}_ip_addr" : options[:ip].to_s
    exists = table.with_column?(name: column)

    return if exists

    register_offense(node, attr, options, column, options[:ip])
  end
end