Skip to content

Commit

Permalink
Fix double registration of :turbo_stream Renderer
Browse files Browse the repository at this point in the history
When an application loads both `ActionController::Base` and
`ActionController::API`, the `:action_controller` load hook gets called
twice (once for each of them). Since the `:turbo_stream` Renderer is
registered in this load hook, it ends up getting registered twice and
prints a warning for method redefinition.

To demonstrate the warning in the `turbo-rails` tests, an
`Api::ApplicationController` was added to the dummy app so that both
base controller classes get loaded:

```
$ CI=true bundle exec rake test
/home/hartley/.cache/asdf/installs/ruby/3.3.0/lib/ruby/gems/3.3.0/gems/actionpack-7.1.3/lib/action_controller/metal/renderers.rb:75: warning: method redefined; discarding old _render_with_renderer_turbo_stream
/home/hartley/src/github.com/skipkayhil/turbo-rails/lib/turbo/engine.rb:67: warning: previous definition of _render_with_renderer_turbo_stream was here
```

This commit fixes the issue by not using the `:action_controller` load
hook to register the `:turbo_stream` Renderer. Adding a Renderer should
not require a lazy load hook because `ActionController::Renderers` does
not load any other classes.
  • Loading branch information
skipkayhil committed Jan 23, 2024
1 parent 38f03b8 commit 79b0fb9
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
8 changes: 3 additions & 5 deletions lib/turbo/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,9 @@ class Engine < Rails::Engine
end

initializer "turbo.renderer" do
ActiveSupport.on_load(:action_controller) do
ActionController::Renderers.add :turbo_stream do |turbo_streams_html, options|
self.content_type = Mime[:turbo_stream] if media_type.nil?
turbo_streams_html
end
ActionController::Renderers.add :turbo_stream do |turbo_streams_html, options|
self.content_type = Mime[:turbo_stream] if media_type.nil?
turbo_streams_html
end
end

Expand Down
2 changes: 2 additions & 0 deletions test/dummy/app/controllers/api/application_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class Api::ApplicationController < ActionController::API
end

0 comments on commit 79b0fb9

Please sign in to comment.