From 18e6f2e5ca8ed80ef49b108beed3b8a180bea5d1 Mon Sep 17 00:00:00 2001 From: Kasper Timm Hansen Date: Tue, 10 Dec 2024 14:58:00 +0100 Subject: [PATCH] Preliminary refactor --- lib/active_record/associated_object.rb | 26 +++++++++++++------------- test/boot/associated_object.rb | 3 +++ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/lib/active_record/associated_object.rb b/lib/active_record/associated_object.rb index 9747090..4008622 100644 --- a/lib/active_record/associated_object.rb +++ b/lib/active_record/associated_object.rb @@ -1,19 +1,19 @@ class ActiveRecord::AssociatedObject class << self - def inherited(klass) - record_klass = klass.module_parent - record_name = klass.module_parent_name.demodulize.underscore - attribute_name = klass.to_s.demodulize.underscore.to_sym - - unless record_klass.respond_to?(:descends_from_active_record?) && record_klass.descends_from_active_record? - raise ArgumentError, "#{record_klass} isn't valid; can only associate with ActiveRecord::Base subclasses" - end - - klass.alias_method record_name, :record - klass.define_singleton_method(:record_klass) { record_klass } - klass.define_singleton_method(:attribute_name) { attribute_name } - klass.delegate :record_klass, :attribute_name, to: :class + def associate_with_record + record_klass = module_parent + record_name = module_parent_name.demodulize.underscore + attribute_name = to_s.demodulize.underscore.to_sym + + raise ArgumentError, "#{record_klass} isn't valid; can only associate with ActiveRecord::Base subclasses" \ + unless record_klass.respond_to?(:descends_from_active_record?) && record_klass.descends_from_active_record? + + alias_method record_name, :record + define_singleton_method(:record_klass) { record_klass } + define_singleton_method(:attribute_name) { attribute_name } + delegate :record_klass, :attribute_name, to: :class end + def inherited(klass) = klass.associate_with_record def extension(&block) record_klass.class_eval(&block) diff --git a/test/boot/associated_object.rb b/test/boot/associated_object.rb index d723278..4d8cd43 100644 --- a/test/boot/associated_object.rb +++ b/test/boot/associated_object.rb @@ -1,5 +1,8 @@ class ApplicationRecord::AssociatedObject < ActiveRecord::AssociatedObject; end +p ApplicationRecord::AssociatedObject.record_klass +p ApplicationRecord::AssociatedObject.attribute_name + class Author::Archiver < ApplicationRecord::AssociatedObject; end # TODO: Replace with Data.define once on Ruby 3.2. Author::Classified = Struct.new(:author)