-
Notifications
You must be signed in to change notification settings - Fork 534
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: separate polymorphic functions (#1433)
* refactor: lookup polymorphic types only once * refactor: polymorphic lookups to utility module * refactor: separate polymorphic functions * Refactor into PolymorphicTypesLookup --------- Co-authored-by: lgebhardt <[email protected]>
- Loading branch information
Showing
4 changed files
with
33 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |