From 200f91ba8ee5a189a7bcf9c51c5f25548c201ff5 Mon Sep 17 00:00:00 2001 From: Sebastian Wilgosz Date: Thu, 7 Dec 2023 16:25:19 +0100 Subject: [PATCH] Fix: Add support for rendering multiple scopes by passing string as names Resolves: #252 --- lib/hanami/view/scope_builder.rb | 4 ++-- spec/integration/scope_builder_spec.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/hanami/view/scope_builder.rb b/lib/hanami/view/scope_builder.rb index 8d464eb0..1486da5d 100644 --- a/lib/hanami/view/scope_builder.rb +++ b/lib/hanami/view/scope_builder.rb @@ -31,7 +31,7 @@ def scope_class(name = nil, rendering:) elsif name.is_a?(Class) name else - View.cache.fetch_or_store(:scope_class, rendering.config) do + View.cache.fetch_or_store("scope_class: #{name}", rendering.config) do resolve_scope_class(name: name, rendering: rendering) end end @@ -40,7 +40,7 @@ def scope_class(name = nil, rendering:) def resolve_scope_class(name:, rendering:) name = rendering.inflector.camelize(name.to_s) - namespace = rendering.config.scope_namespace + namespace = rendering.config.scope_namespace || Object # Give autoloaders a chance to act begin diff --git a/spec/integration/scope_builder_spec.rb b/spec/integration/scope_builder_spec.rb index 63d96d26..c15a1652 100644 --- a/spec/integration/scope_builder_spec.rb +++ b/spec/integration/scope_builder_spec.rb @@ -27,5 +27,31 @@ expect(scope).to be_an_instance_of scope_class end + + context 'when multiple scopes are rendered in the same view' do + + let(:builder) { described_class.new } + + it 'allows to build scopes with different classes' do + FirstScopeClass = Class.new(Hanami::View::Scope) + SecondScopeClass = Class.new(Hanami::View::Scope) + + view = Class.new(Hanami::View) do + config.paths = SPEC_ROOT.join("__ignore__") + config.template = "__ignore__" + + config.scope_class = FirstScopeClass + end.new + + scope = view.rendering.scope({}) + expect(scope).to be_an_instance_of FirstScopeClass + + scope = view.rendering.scope('SecondScopeClass', {}) + expect(scope).to be_an_instance_of SecondScopeClass + + scope = view.rendering.scope('FirstScopeClass', {}) + expect(scope).to be_an_instance_of FirstScopeClass + end + end end end