Class: RuboCop::Cop::YiffSpace::UserToId

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

Overview

Detects the ternary pattern ‘x.is_a?(User) ? x.id : x` and enforces use of the `u2id` helper instead, which handles both User objects and raw IDs without the inline type check.

Examples:

# bad
user.is_a?(User) ? user.id : user

# bad
creator.is_a?(User) ? creator.id : creator

# good
u2id(user)

# good
u2id(creator)

Constant Summary collapse

MSG =
"Use `u2id(%<var>s)` instead of `%<original>s`"

Constants included from NodeFormattingHelper

NodeFormattingHelper::BASIC

Instance Method Summary collapse

Methods included from NodeFormattingHelper

#format_node

Instance Method Details

#on_if(node) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rubocop/cop/yiff_space/user_to_id.rb', line 33

def on_if(node)
  return unless node.ternary?

  return unless user_check?(node.condition)
  return unless id_call?(node.if_branch)
  return unless same_value?(node.if_branch.receiver, node.else_branch)

  message = format(MSG, var: node.else_branch.source, original: node.source)
  add_offense(node, message: message) do |corrector|
    corrector.replace(node, "u2id(#{node.else_branch.source})")
  end
end