Skip to content

Commit

Permalink
Duplicate the context hash when duplicating an Attacher (#653)
Browse files Browse the repository at this point in the history
Without this change, a single context hash is shared between the original attacher and its duplicate. The changes in fc6a3ed update this shared hash after duplication to reference the duplicate model, leading to both the duplicate and original attacher having `context[:record]` pointing at the duplicated model.
  • Loading branch information
reidab authored Sep 17, 2023
1 parent b586fb2 commit bf43c6d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/shrine/attacher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,13 @@ def shrine_class

private

# The copy constructor that's called on #dup and #clone
# We need to duplicate the context to prevent it from being shared
def initialize_copy(other)
super
@context = @context.dup
end

# Converts a String or Hash value into an UploadedFile object and ensures
# it's uploaded to temporary storage.
#
Expand Down
7 changes: 7 additions & 0 deletions test/attacher_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@
@shrine = @attacher.shrine_class
end

describe '#initialize_copy' do
it 'duplicates the context when duplicating the attacher' do
attacher_copy = @attacher.dup
refute_equal @attacher.context.object_id, attacher_copy.context.object_id
end
end

describe ".from_data" do
it "instantiates an attacher from file data" do
file = @attacher.upload(fakeio)
Expand Down
1 change: 1 addition & 0 deletions test/plugin/model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@
assert_equal model_copy, model_copy.file_attacher.record
assert_equal :file, model_copy.file_attacher.name
assert_equal Hash[record: model_copy, name: :file], model_copy.file_attacher.context
assert_equal Hash[record: model, name: :file], model.file_attacher.context
assert model_copy.file_attacher.changed? # retains any state
end

Expand Down

0 comments on commit bf43c6d

Please sign in to comment.