Skip to content

Commit

Permalink
Preliminary refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
kaspth committed Dec 10, 2024
1 parent f9204ca commit 18e6f2e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
26 changes: 13 additions & 13 deletions lib/active_record/associated_object.rb
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
3 changes: 3 additions & 0 deletions test/boot/associated_object.rb
Original file line number Diff line number Diff line change
@@ -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)
Expand Down

0 comments on commit 18e6f2e

Please sign in to comment.