Skip to content

Commit

Permalink
Allow #reload and #initialize_dup to be overriden safely in model. Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
mshibuya committed May 16, 2019
1 parent 12d48d7 commit eb9c52e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
12 changes: 9 additions & 3 deletions lib/carrierwave/orm/activerecord.rb
Expand Up @@ -12,7 +12,9 @@ module ActiveRecord
def mount_uploader(column, uploader=nil, options={}, &block)
super

class_eval <<-RUBY, __FILE__, __LINE__+1
mod = Module.new
prepend mod
mod.class_eval <<-RUBY, __FILE__, __LINE__+1
def remote_#{column}_url=(url)
column = _mounter(:#{column}).serialization_column
__send__(:"\#{column}_will_change!")
Expand All @@ -27,7 +29,9 @@ def remote_#{column}_url=(url)
def mount_uploaders(column, uploader=nil, options={}, &block)
super

class_eval <<-RUBY, __FILE__, __LINE__+1
mod = Module.new
prepend mod
mod.class_eval <<-RUBY, __FILE__, __LINE__+1
def remote_#{column}_urls=(url)
column = _mounter(:#{column}).serialization_column
__send__(:"\#{column}_will_change!")
Expand Down Expand Up @@ -59,7 +63,9 @@ def mount_base(column, uploader=nil, options={}, &block)
after_commit :"remove_previously_stored_#{column}", :on => :update
after_commit :"store_#{column}!", :on => [:create, :update]

class_eval <<-RUBY, __FILE__, __LINE__+1
mod = Module.new
prepend mod
mod.class_eval <<-RUBY, __FILE__, __LINE__+1
def #{column}=(new_file)
column = _mounter(:#{column}).serialization_column
if !(new_file.blank? && __send__(:#{column}).blank?)
Expand Down
42 changes: 41 additions & 1 deletion spec/orm/activerecord_spec.rb
Expand Up @@ -1604,13 +1604,53 @@ def filename
end
end

describe '#reload' do
before do
Event.mount_uploader(:image, @uploader)
end

context 'when #reload is overriden in the model' do
before do
Event.class_eval do
def reload(*)
super
end
end
@event.save
@event.image
end

it "clears @_mounters" do
expect { @event.reload }.to change { @event.instance_variable_get(:@_mounters) }.to(nil)
end
end
end

describe "#dup" do
it "appropriately removes the model reference from the new models uploader" do
before do
Event.mount_uploader(:image, @uploader)
end

it "appropriately removes the model reference from the new models uploader" do
@event.save
new_event = @event.dup

expect(new_event.image.model).not_to eq @event
end

context 'when #initialize_dup is overriden in the model' do
before do
Event.class_eval do
def initialize_dup(*)
super
end
end
@event.image
end

it "clears @_mounters" do
expect(@event.dup.instance_variable_get(:@_mounters)).to be_blank
end
end
end
end

0 comments on commit eb9c52e

Please sign in to comment.