diff --git a/lib/jsonapi-resources.rb b/lib/jsonapi-resources.rb index 04d7908f..e26af1aa 100644 --- a/lib/jsonapi-resources.rb +++ b/lib/jsonapi-resources.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require 'jsonapi/resources/railtie' +require 'jsonapi/utils/polymorphic_types_lookup' require 'jsonapi/naive_cache' require 'jsonapi/compiled_json' require 'jsonapi/relation_retrieval' diff --git a/lib/jsonapi/relationship.rb b/lib/jsonapi/relationship.rb index 31a053b2..da706523 100644 --- a/lib/jsonapi/relationship.rb +++ b/lib/jsonapi/relationship.rb @@ -87,17 +87,7 @@ def inverse_relationship end def self.polymorphic_types(name) - @poly_hash ||= {}.tap do |hash| - ObjectSpace.each_object do |klass| - next unless Module === klass - if ActiveRecord::Base > klass - klass.reflect_on_all_associations(:has_many).select { |r| r.options[:as] }.each do |reflection| - (hash[reflection.options[:as]] ||= []) << klass.name.underscore - end - end - end - end - @poly_hash[name.to_sym] + ::JSONAPI::Utils::PolymorphicTypesLookup.polymorphic_types(name) end def resource_types diff --git a/lib/jsonapi/resource_common.rb b/lib/jsonapi/resource_common.rb index c4731df1..85c81361 100644 --- a/lib/jsonapi/resource_common.rb +++ b/lib/jsonapi/resource_common.rb @@ -1020,17 +1020,7 @@ def polymorphic(polymorphic = true) end def _polymorphic_types - @poly_hash ||= {}.tap do |hash| - ObjectSpace.each_object do |klass| - next unless Module === klass - if klass < ActiveRecord::Base - klass.reflect_on_all_associations(:has_many).select{|r| r.options[:as] }.each do |reflection| - (hash[reflection.options[:as]] ||= []) << klass.name.underscore - end - end - end - end - @poly_hash[_polymorphic_name.to_sym] + JSONAPI::Utils.polymorphic_types(_polymorphic_name.to_sym) end def _polymorphic_resource_klasses diff --git a/lib/jsonapi/utils/polymorphic_types_lookup.rb b/lib/jsonapi/utils/polymorphic_types_lookup.rb new file mode 100644 index 00000000..2a72673e --- /dev/null +++ b/lib/jsonapi/utils/polymorphic_types_lookup.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +module JSONAPI + module Utils + module PolymorphicTypesLookup + extend self + + def polymorphic_types(name) + polymorphic_types_lookup[name.to_sym] + end + + def polymorphic_types_lookup + @polymorphic_types_lookup ||= build_polymorphic_types_lookup + end + + def build_polymorphic_types_lookup + {}.tap do |hash| + ObjectSpace.each_object do |klass| + next unless Module === klass + if ActiveRecord::Base > klass + klass.reflect_on_all_associations(:has_many).select { |r| r.options[:as] }.each do |reflection| + (hash[reflection.options[:as]] ||= []) << klass.name.underscore + end + end + end + end + end + end + end +end