Skip to content

Instantly share code, notes, and snippets.

@leandro
Created March 4, 2023 21:16
Show Gist options
  • Save leandro/916b5e3b6eae899dcc427b3534557469 to your computer and use it in GitHub Desktop.
Save leandro/916b5e3b6eae899dcc427b3534557469 to your computer and use it in GitHub Desktop.
Dirty graceful method overriding approach
# 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