MONGOID-5734 Custom polymorphic types #5845
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds support for custom polymorphic types via a global registry. While polymorphic type keys still default to the fully qualified name of the class, it is now possible to specify different aliases by which a polymorphic type might be identified in the database.
For example, consider a simple data model involving a manager, a department, and a team:
Each document in the
managers
collection will include two fields,unit_id
andunit_type
, where theunit_type
field names the class (and thus, indirectly, the collection) of the unit that the manager is in charge of. For example:Inspecting
tina.unit_type
would return the string"Team"
.With this PR, programmers may now specify alternative keys to represent different classes, thus decoupling the code from the data. For example:
The
identify_as 'dept'
directive says that this class should be identified by the string"dept"
in the database. You can specify multiple aliases, too (e.g.identify_as 'dept', 'div', 'agency'
), in which case the first key is the "default", and the others are only used for looking up records. This lets you refactor your code without breaking the associations in your data.It is important to note that these aliases are global. The keys you specify must be unique across your entire code base. However, it is possible to register alternate resolvers, which may be used for different subsets of your models. In this case, the keys must only be unique for each resolver. For example:
Both
Engineering::Department
andPurchasing::Department
are aliased as"dept"
, but use their own resolver, so there is no conflict.