Created
July 18, 2024 08:45
-
-
Save DangerDawson/46164ba54de58e8a697d2ecb9f36a02e to your computer and use it in GitHub Desktop.
ROM relations optimisation 1
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
module ROM | |
class Finalize | |
class FinalizeRelations | |
include Dry::Core::Memoizable | |
# @return [Hash] | |
# | |
# @api private | |
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize | |
def run! | |
relation_registry = RelationRegistry.new do |registry, relations| | |
@relation_classes.each do |klass| | |
unless klass.adapter | |
raise MissingAdapterIdentifierError, | |
"Relation class +#{klass}+ is missing the adapter identifier" | |
end | |
key = klass.relation_name.to_sym | |
if registry.key?(key) | |
raise RelationAlreadyDefinedError, | |
"Relation with name #{key.inspect} registered more than once" | |
end | |
klass.use(:registry_reader, klass: klass, relations: relation_names) | |
notifications.trigger('configuration.relations.class.ready', relation: klass, adapter: klass.adapter) | |
relations[key] = build_relation(klass, registry) | |
end | |
registry.each do |_, relation| | |
notifications.trigger( | |
'configuration.relations.object.registered', | |
relation: relation, registry: registry | |
) | |
end | |
end | |
notifications.trigger( | |
'configuration.relations.registry.created', registry: relation_registry | |
) | |
relation_registry | |
end | |
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize | |
def relation_names | |
@relation_classes.map(&:relation_name).map(&:relation).uniq | |
end | |
memoize :relation_names | |
end | |
end | |
end | |
module ROM | |
module Plugins | |
module Relation | |
class RegistryReader | |
extend Dry::Core::ClassAttributes | |
defines :relation_readers | |
defines :mutex | |
mutex(Mutex.new) | |
def mutex | |
self.class.mutex | |
end | |
# @api private | |
def initialize(klass:, relations:) | |
mutex.synchronize do | |
self.class.relation_readers(build_relation_readers(relations)) unless self.class.relation_readers | |
end | |
klass.include self.class.relation_readers | |
end | |
def build_relation_readers(relations) | |
Module.new do | |
relations.each do |name| | |
define_method(name) { __registry__[name] } | |
end | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment