|
1 | 1 | module React |
2 | 2 | module Rails |
| 3 | + # This module is included into ActionController so that |
| 4 | + # per-request hooks can be called in the view helper. |
3 | 5 | module ControllerLifecycle |
4 | 6 | extend ActiveSupport::Concern |
5 | 7 |
|
6 | 8 | included do |
7 | 9 | # use both names to support Rails 3..5 |
8 | | - before_action_with_fallback = respond_to?(:before_action) ? :before_action : :before_filter |
9 | | - after_action_with_fallback = respond_to?(:after_action) ? :after_action : :after_filter |
10 | | - public_send(before_action_with_fallback, :setup_react_component_helper) |
11 | | - public_send(after_action_with_fallback, :teardown_react_component_helper) |
| 10 | + around_action_with_fallback = respond_to?(:around_action) ? :around_action : :around_filter |
| 11 | + public_send(around_action_with_fallback, :use_react_component_helper) |
12 | 12 | attr_reader :__react_component_helper |
13 | 13 | end |
14 | 14 |
|
15 | | - def setup_react_component_helper |
| 15 | + module ClassMethods |
| 16 | + # Call this in the controller to check out a prerender for the whole request. |
| 17 | + # You can access the renderer with {#react_rails_prerenderer}. |
| 18 | + def per_request_react_rails_prerenderer |
| 19 | + around_action_with_fallback = respond_to?(:around_action) ? :around_action : :around_filter |
| 20 | + public_send(around_action_with_fallback, :per_request_react_rails_prerenderer) |
| 21 | + end |
| 22 | + end |
| 23 | + |
| 24 | + # Instantiate the ViewHelper implementation and call its #setup method |
| 25 | + # then let the controller action run, |
| 26 | + # then call the ViewHelper implementation's #teardown method |
| 27 | + def use_react_component_helper |
16 | 28 | new_helper = React::Rails::ViewHelper.helper_implementation_class.new |
17 | 29 | new_helper.setup(self) |
18 | 30 | @__react_component_helper = new_helper |
| 31 | + yield |
| 32 | + @__react_component_helper.teardown(self) |
19 | 33 | end |
20 | 34 |
|
21 | | - def teardown_react_component_helper |
22 | | - @__react_component_helper.teardown(self) |
| 35 | + # If you want a per-request renderer, add this method as an around-action |
| 36 | + # |
| 37 | + # (`.per_request_react_rails_prerenderer` does this for you) |
| 38 | + # @example Having one renderer instance for each controller action |
| 39 | + # around_action :per_request_react_rails_prerenderer |
| 40 | + def per_request_react_rails_prerenderer |
| 41 | + React::ServerRendering.with_renderer do |renderer| |
| 42 | + @__react_rails_prerenderer = renderer |
| 43 | + yield |
| 44 | + end |
| 45 | + end |
| 46 | + |
| 47 | + |
| 48 | + # An instance of a server renderer, for use during this request |
| 49 | + def react_rails_prerenderer |
| 50 | + @__react_rails_prerenderer |
23 | 51 | end |
24 | 52 | end |
25 | 53 | end |
|
0 commit comments