Skip to content

Commit

Permalink
Optimise the repository relations reader
Browse files Browse the repository at this point in the history
  • Loading branch information
DangerDawson committed Jul 22, 2024
1 parent fbd8d2e commit a39ac5c
Showing 1 changed file with 34 additions and 8 deletions.
42 changes: 34 additions & 8 deletions repository/lib/rom/repository/relation_reader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,50 @@ module ROM
class Repository
# @api private
class RelationReader < Module
extend Dry::Core::ClassAttributes

# @api private
attr_reader :klass

# @api private
attr_reader :relations

defines :relation_readers

defines :mutex
mutex(Mutex.new)

defines :relation_cache
relation_cache(Concurrent::Hash.new)

module InstanceMethods
# @api private
def set_relation(name)
container
.relations[name]
.with(auto_struct: auto_struct)
.struct_namespace(struct_namespace)
.with(auto_struct: auto_struct, struct_namespace: struct_namespace)
end

def relation_reader(name, relation_cache)
key = [name, auto_struct, struct_namespace]
relation_cache[key] ||= set_relation(name)
end
end

# @api private
def mutex
ROM::Repository::RelationReader.mutex
end

# @api private
def initialize(klass, relations)
@klass = klass
@relations = relations
define_readers!
mutex.synchronize do
unless self.class.relation_readers
self.class.relation_readers(build_relation_readers(relations, self.class.relation_cache))
end
end
klass.include self.class.relation_readers
end

# @api private
Expand All @@ -33,13 +56,16 @@ def included(klass)
klass.include(InstanceMethods)
end


private

# @api private
def define_readers!
relations.each do |name|
define_method(name) do
@relations[name] ||= set_relation(name)
def build_relation_readers(relations, relation_cache)
Module.new do
relations.each do |name|
define_method(name) do
relation_reader(name, relation_cache)
end
end
end
end
Expand Down

0 comments on commit a39ac5c

Please sign in to comment.