Skip to content

Commit ea43daa

Browse files
committed
Add a public writer for ActiveStorage::Service::DiskService#root
Extracted from rails#41543. In that PR, I introduce docs on how to test Active Storage in a variety of scenarios. One specific case is when you're doing parallel tests. To avoid the files uploaded / deleted in your tests from clashing with each other, you should have each test run with a separate storage directory. Currently `ActiveStorage::Service::DiskService#root` is readonly, which means that to do that you need to change it using `instance_variable_set`. This isn't very elegant. Given parallel tests and Active Storage are both turned on by default in Rails I think it makes sense to have a nice API for this. This PR just changes the `attr_reader` to an `attr_accessor`. With this change, the [code sample here](https://github.com/rails/rails/pull/41543/files#diff-e61fcdded4b6112b041ff388609c7032d09b8212ce209d67a7debc32f230d77aR1059-R1061) works.
1 parent 917e81a commit ea43daa

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

activestorage/lib/active_storage/service/disk_service.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ module ActiveStorage
99
# Wraps a local disk path as an Active Storage service. See ActiveStorage::Service for the generic API
1010
# documentation that applies to all services.
1111
class Service::DiskService < Service
12-
attr_reader :root
12+
attr_accessor :root
1313

1414
def initialize(root:, public: false, **options)
1515
@root = root

activestorage/test/service/disk_service_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,17 @@ class ActiveStorage::Service::DiskServiceTest < ActiveSupport::TestCase
2626
test "headers_for_direct_upload generation" do
2727
assert_equal({ "Content-Type" => "application/json" }, @service.headers_for_direct_upload(@key, content_type: "application/json"))
2828
end
29+
30+
test "root" do
31+
assert_equal tmp_config.dig(:tmp, :root), @service.root
32+
end
33+
34+
test "can change root" do
35+
tmp_path_2 = File.join(Dir.tmpdir, "active_storage_2")
36+
@service.root = tmp_path_2
37+
38+
assert_equal tmp_path_2, @service.root
39+
ensure
40+
@service.root = tmp_config.dig(:tmp, :root)
41+
end
2942
end

0 commit comments

Comments
 (0)