diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 4261518d8..a92c45826 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,6 +9,10 @@ title: Changelog
## main
+* Prevent adding duplicates to `autoload_paths`.
+
+ *Thomas Hutterer*
+
* Add FreeAgent to list of companies using ViewComponent.
*Simon Fish*
diff --git a/docs/index.md b/docs/index.md
index e058c5d5d..3323cc908 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -188,6 +188,7 @@ ViewComponent is built by over a hundred members of the community, including:
+
diff --git a/lib/view_component/engine.rb b/lib/view_component/engine.rb
index 6aab1132f..af3952496 100644
--- a/lib/view_component/engine.rb
+++ b/lib/view_component/engine.rb
@@ -77,7 +77,8 @@ class Engine < Rails::Engine # :nodoc:
options = app.config.view_component
if options.show_previews && !options.preview_paths.empty?
- ActiveSupport::Dependencies.autoload_paths.concat(options.preview_paths)
+ paths_to_add = options.preview_paths - ActiveSupport::Dependencies.autoload_paths
+ ActiveSupport::Dependencies.autoload_paths.concat(paths_to_add) if paths_to_add.any?
end
end
diff --git a/test/sandbox/config/application.rb b/test/sandbox/config/application.rb
index cfcb0e99f..84ae7620c 100644
--- a/test/sandbox/config/application.rb
+++ b/test/sandbox/config/application.rb
@@ -17,6 +17,10 @@
module Sandbox
class Application < Rails::Application
config.action_controller.asset_host = "http://assets.example.com"
+
+ # Prepare test_set_no_duplicate_autoload_paths
+ config.autoload_paths.push("#{config.root}/my/components/previews")
+ config.view_component.preview_paths << "#{config.root}/my/components/previews"
end
end
diff --git a/test/sandbox/test/initializers/engine_test.rb b/test/sandbox/test/initializers/engine_test.rb
new file mode 100644
index 000000000..ce030c3f7
--- /dev/null
+++ b/test/sandbox/test/initializers/engine_test.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class EngineTest < Minitest::Test
+ def test_set_no_duplicate_autoload_paths
+ test_path = "#{Rails.root}/my/components/previews" # set in sandbox/config/application.rb
+ assert_equal 1, ActiveSupport::Dependencies.autoload_paths.count(test_path)
+ end
+end