Skip to content

Commit

Permalink
fix: more flexible polymorphic types lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
bf4 committed Dec 31, 2023
1 parent 7e75993 commit a140f14
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions lib/jsonapi/relationship.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,14 +90,37 @@ def self.polymorphic_types(name)
@poly_hash ||= {}.tap do |hash|
ObjectSpace.each_object do |klass|
next unless Module === klass
if ActiveRecord::Base > klass
is_active_record_inspectable = ActiveRecord::Base > klass
is_active_record_inspectable &&= klass.respond_to?(:reflect_on_all_associations, true)
is_active_record_inspectable &&= format_polymorphic_klass_type(klass).present?
if is_active_record_inspectable
klass.reflect_on_all_associations(:has_many).select { |r| r.options[:as] }.each do |reflection|
(hash[reflection.options[:as]] ||= []) << klass.name.underscore
(hash[reflection.options[:as]] ||= []) << format_polymorphic_klass_type(klass).underscore
end
end
end
end
@poly_hash[name.to_sym]
@poly_hash.fetch(name.to_sym) do
klass = name.classify.safe_constantize
if klass.nil?
warn "[POLYMORPHIC TYPE NOT FOUND] No polymorphic types found for #{name}"
else
polymorphic_type = format_polymorphic_klass_type(klass)
warn "[POLYMORPHIC TYPE] Found polymorphic types through reflection for #{name}: #{polymorphic_type}"
@poly_hash[name.to_sym] = [polymorphic_type]
end
end
end

def format_polymorphic_klass_type(klass)
klass.name ||
begin
klass.model_name.name
rescue ArgumentError => ex
# klass.base_class may be nil
warn "[POLYMORPHIC TYPE] #{__callee__} #{klass} #{ex.inspect}"
nil
end
end

def resource_types
Expand Down Expand Up @@ -203,7 +226,7 @@ def polymorphic_type
def setup_implicit_relationships_for_polymorphic_types(exclude_linkage_data: true)
types = self.class.polymorphic_types(_relation_name)
unless types.present?
warn "No polymorphic types found for #{parent_resource.name} #{_relation_name}"
warn "[POLYMORPHIC TYPE] No polymorphic types found for #{parent_resource.name} #{_relation_name}"
return
end

Expand Down

0 comments on commit a140f14

Please sign in to comment.