Skip to content

Commit

Permalink
Raise a helpful error if you access context before rendering (#863)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
joeldrapper authored Feb 16, 2025
1 parent ef0de17 commit 0fb1d3c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/phlex/sgml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions quickdraw/context.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,13 @@

assert_equal_html b.new.call, %(<h1>Hello, World!</h1>)
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

0 comments on commit 0fb1d3c

Please sign in to comment.