From d54436e16a232beef815d59abd5ab7b7033f7a99 Mon Sep 17 00:00:00 2001 From: Will Cosgrove Date: Tue, 30 Jan 2024 20:21:08 -0600 Subject: [PATCH] Add `view_context` to `Phlex::Context` --- lib/phlex/rails.rb | 4 ++++ lib/phlex/rails/context/overrides.rb | 16 ++++++++++++++++ lib/phlex/rails/sgml/overrides.rb | 13 +++++++++---- 3 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 lib/phlex/rails/context/overrides.rb diff --git a/lib/phlex/rails.rb b/lib/phlex/rails.rb index 30e26f98..cbe901ac 100644 --- a/lib/phlex/rails.rb +++ b/lib/phlex/rails.rb @@ -32,4 +32,8 @@ class HTML class Unbuffered prepend ::Phlex::Rails::UnbufferedOverrides end + + class Context + prepend ::Phlex::Rails::Context::Overrides + end end diff --git a/lib/phlex/rails/context/overrides.rb b/lib/phlex/rails/context/overrides.rb new file mode 100644 index 00000000..970e6f3d --- /dev/null +++ b/lib/phlex/rails/context/overrides.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +module Phlex + module Rails + module Context + module Overrides + def initialize(...) + super + @view_context = nil + end + + attr_accessor :view_context + end + end + end +end diff --git a/lib/phlex/rails/sgml/overrides.rb b/lib/phlex/rails/sgml/overrides.rb index f27d7a33..2da4e158 100644 --- a/lib/phlex/rails/sgml/overrides.rb +++ b/lib/phlex/rails/sgml/overrides.rb @@ -5,10 +5,10 @@ module Rails module SGML module Overrides def helpers - if defined?(ViewComponent::Base) && @_view_context.is_a?(ViewComponent::Base) - @_view_context.helpers + if defined?(ViewComponent::Base) && @_context.view_context.is_a?(ViewComponent::Base) + @_context.view_context.helpers else - @_view_context + @_context.view_context end end @@ -24,7 +24,7 @@ def render(*args, **kwargs, &block) return super unless renderable.is_a?(ActiveRecord::Relation) else captured_block = -> { capture(&block) } if block - @_context.target << @_view_context.render(*args, **kwargs, &captured_block) + @_context.target << @_context.view_context.render(*args, **kwargs, &captured_block) end nil @@ -57,6 +57,11 @@ def render_in(view_context, &block) end end + def __final_call__(buffer = +"", context: Phlex::Context.new, view_context: nil, **kwargs, &block) + context.view_context ||= view_context + super(buffer, context: context, **kwargs, &block) + end + def capture super&.html_safe end