Created
March 4, 2023 21:16
-
-
Save leandro/916b5e3b6eae899dcc427b3534557469 to your computer and use it in GitHub Desktop.
Dirty graceful method overriding approach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module Importer | |
module Preloadable | |
extend ActiveSupport::Concern | |
included do | |
delegate :preloader_settings, to: :class | |
delegate :preloaded_records_manager, to: :import_service | |
def self.method_added(method_name) | |
return if method_name != :initialize | |
return if 'preloadable'.in?(Array(instance_method(:initialize).source_location).first) | |
class_exec do | |
alias_method :original_initialize, :initialize | |
def initialize(...) | |
original_initialize(...) | |
preload_referenced_records! | |
end | |
end | |
end | |
end | |
private | |
def preloader = @preloader ||= preloaded_records_manager.preloader_by(self) | |
def preload_referenced_records! | |
preloaded_records_manager.register_preloader(self)&.preload | |
end | |
class_methods do | |
attr_reader :preloader_settings | |
private | |
def preload_existing_records_by(settings) = @preloader_settings = settings | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment