class RuboCop::Cop::Rails::ActiveSupportOnLoad
ActiveSupport.on_load(:active_record) { include MyClass }
# good
ActiveRecord::Base.include(MyClass)
# bad
@example
load order dependency bugs.
While using lazy load hooks is recommended, it changes the order in which is code is loaded and may reveal
@safety
patching forcibly loads the framework referenced, using hooks defers loading until it’s actually needed.
Checks for Rails framework classes that are patched directly instead of using Active Support load hooks. Direct
def hook_for_const(const_name)
def hook_for_const(const_name) hook = LOAD_HOOKS[const_name] hook ||= RAILS_5_2_LOAD_HOOKS[const_name] if target_rails_version >= 5.2 hook ||= RAILS_7_1_LOAD_HOOKS[const_name] if target_rails_version >= 7.1 hook end
def on_send(node)
def on_send(node) receiver, method, arguments = *node # rubocop:disable InternalAffairs/NodeDestructuring return unless arguments && (hook = hook_for_const(receiver&.const_name)) preferred = "ActiveSupport.on_load(:#{hook}) { #{method} #{arguments.source} }" add_offense(node, message: format(MSG, prefer: preferred, current: node.source)) do |corrector| corrector.replace(node, preferred) end end