From 0fb1d3c715adf83492663c68cf03495804a71834 Mon Sep 17 00:00:00 2001 From: Joel Drapper Date: Sun, 16 Feb 2025 12:27:55 +0000 Subject: [PATCH] Raise a helpful error if you access `context` before rendering (#863) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If you access the `context` before rendering, the error message says `nil` doesn’t respond to `user_context`. This PR makes `context` return `nil` instead. Opening as a draft as I want to write a test for this before merging. --- lib/phlex/sgml.rb | 14 +++++++++++++- quickdraw/context.test.rb | 10 ++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/phlex/sgml.rb b/lib/phlex/sgml.rb index 76e9b800..2b27a90f 100644 --- a/lib/phlex/sgml.rb +++ b/lib/phlex/sgml.rb @@ -94,7 +94,19 @@ def internal_call(parent: nil, state: nil, &block) end def context - @_state.user_context + if rendering? + @_state.user_context + else + raise Phlex::ArgumentError.new(<<~MESSAGE) + You can’t access the context before the component has started rendering. + MESSAGE + end + end + + # Returns `false` before rendering and `true` once the component has started rendering. + # It will not reset back to false after rendering. + def rendering? + !!@_state end # Output plain text. diff --git a/quickdraw/context.test.rb b/quickdraw/context.test.rb index 2fbae52b..6c527d2e 100644 --- a/quickdraw/context.test.rb +++ b/quickdraw/context.test.rb @@ -27,3 +27,13 @@ assert_equal_html b.new.call, %(

Hello, World!

) end + +test "raises an ArgumentError if you access the context before rendering" do + component = Phlex::HTML.new + + error = assert_raises(Phlex::ArgumentError) { component.context } + + assert_equal error.message, <<~MESSAGE + You can’t access the context before the component has started rendering. + MESSAGE +end