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, %(