-
-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Rails] Explain how to render without a view context
- Loading branch information
1 parent
19392a0
commit 1ac002c
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
Most Rails renders are synchronous responses to user requests. In these synchronous contexts, the `render` method is defined and an `ActionView::Context` is present. We need these two things to render Phlex components. | ||
|
||
However, these two things are not always present. How can we render Phlex components in an ActiveRecord callback? How can we render in a background job? The answer is to use `ApplicationController.render_to_string`. | ||
|
||
Example 1: rendering a Phlex component for a Turbo Stream in response to an ActiveRecord callback: | ||
|
||
``` | ||
class Post < ApplicationRecord | ||
after_create_commit { | ||
model = self | ||
component = Components::MyPostComponent.new(post: model) | ||
# Setting the request is not always required, but common Rails features | ||
# including path helpers fail without it. | ||
fake_rack_request = Rack::MockRequest.env_for("http://localhost", method: :get) | ||
controller.request = ActionDispatch::Request.new(fake_rack_request) | ||
html = controller.render_to_string(component, layout: false) | ||
broadcast_prepend_to("my-streamable", html:) | ||
} | ||
end | ||
``` | ||
|
||
Example 2: rendering a Phlex component in a background job: | ||
``` | ||
class MailJob < ApplicationJob | ||
queue_as :default | ||
def perform(*args) | ||
model = Post.create! | ||
component = Components::MyPostComponent.new(post: model) | ||
fake_rack_request = Rack::MockRequest.env_for("http://localhost", method: :get) | ||
controller.request = ActionDispatch::Request.new(fake_rack_request) | ||
html = controller.render_to_string(component, layout: false) | ||
HelloMailer.with(html:).hello_email.deliver_now | ||
end | ||
end | ||
``` |