Skip to content

Commit

Permalink
Allow explicit as well as non-existent roots
Browse files Browse the repository at this point in the history
  • Loading branch information
timriley committed Jun 1, 2024
1 parent 2932c33 commit f282516
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion lib/hanami/db/repo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ module DB
# @api public
# @since 2.2.0
class Repo < ROM::Repository
# @api public
# @since 2.2.0
def self.[](root)
fetch_or_store(root) do
# Override ROM::Repository.[] logic to ensure repos with explicit roots inherit from
# Hanami::DB::Repo itself, instead of the plain old ROM::Repository::Root.
Class.new(self).tap { |klass|
klass.root(root)
}
end
end

# @api public
# @since 2.2.0
defines :root
Expand All @@ -24,7 +36,17 @@ def self.inherited(klass)
def initialize(*, **)
super

@root = set_relation(self.class.root) if self.class.root
# Repos in Hanami apps infer a root from their class name (e.g. :posts for PostRepo). This
# means _every_ repo ends up with an inferred root, many of which will not exist as
# relations. To avoid errors from fetching these non-existent relations, check first before
# setting the root.
@root = set_relation(self.class.root) if set_relation?(self.class.root)
end

private

def set_relation?(name)
name && container.relations.key?(name)
end
end
end
Expand Down

0 comments on commit f282516

Please sign in to comment.