Class: RuboCop::Cop::YiffSpace::CurrentUserOutsideOfRequests

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/yiff_space/current_user_outside_of_requests.rb

Overview

Prevents use of the CurrentUser class outside of the request cycle. CurrentUser relies on thread-local state set by request middleware and is unavailable in background jobs, rake tasks, or other contexts outside of the request lifecycle.

The class name is configurable via ‘ClassName` (default: `CurrentUser`). References inside the class that defines CurrentUser itself are always ignored. Controllers, views, helpers, presenters, and decorators are excluded by default. Use `IgnoredMethods`, `IgnoredMethodPrefixes`, `IgnoredMethodSuffixes`, or `IgnoredMethodPatterns` to allow CurrentUser in specific methods in checked files.

Examples:

# bad
def process_records
  CurrentUser.id
end

# bad
def notify
  CurrentUser.email
end

# good - inside the CurrentUser class definition itself
class CurrentUser
  def self.id
    RequestStore[:current_user]&.id
  end
end

# good (IgnoredMethodSuffixes: [_current])
def user_current
  CurrentUser.id
end

# good (IgnoredMethodPrefixes: [apionly_])
def apionly_serialize
  CurrentUser.email
end

# good (IgnoredMethodPatterns: [/_current_user_/])
def serialize_current_user_email
  CurrentUser.email
end

Constant Summary collapse

MSG =
"`%<class_name>s` should only be used within the request cycle (controllers, views, helpers, decorators)"

Instance Method Summary collapse

Instance Method Details

#on_const(node) ⇒ Object



66
67
68
69
70
71
72
73
# File 'lib/rubocop/cop/yiff_space/current_user_outside_of_requests.rb', line 66

def on_const(node)
  return unless current_user?(node)
  return if ignored_method?(node)
  return if inside_current_user_class?(node)
  return if node.parent&.send_type? && node.parent.receiver == node

  add_offense(node, message: message)
end

#on_csend(node) ⇒ Object



62
63
64
# File 'lib/rubocop/cop/yiff_space/current_user_outside_of_requests.rb', line 62

def on_csend(node)
  on_send(node)
end

#on_send(node) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/rubocop/cop/yiff_space/current_user_outside_of_requests.rb', line 54

def on_send(node)
  return unless starts_with_current_user?(node)
  return if ignored_method?(node)
  return if inside_current_user_class?(node)

  add_offense(node, message: message)
end