module Shrine::Plugins::Activerecord::AttachmentMethods

  1. lib/shrine/plugins/activerecord.rb

Methods

Public Instance

  1. included

Public Instance methods

included(model)
[show source]
   # File lib/shrine/plugins/activerecord.rb
20 def included(model)
21   super
22 
23   return unless model < ::ActiveRecord::Base
24 
25   name = @name
26 
27   if shrine_class.opts[:activerecord][:validations]
28     model.validate do
29       send(:"#{name}_attacher").send(:activerecord_validate)
30     end
31   end
32 
33   if shrine_class.opts[:activerecord][:callbacks]
34     model.before_save do
35       if send(:"#{name}_attacher").changed?
36         send(:"#{name}_attacher").send(:activerecord_before_save)
37       end
38     end
39 
40     [:create, :update].each do |action|
41       model.after_commit on: action do
42         if send(:"#{name}_attacher").changed?
43           send(:"#{name}_attacher").send(:activerecord_after_save)
44         end
45       end
46     end
47 
48     model.after_commit on: :destroy do
49       if send(:"#{name}_attacher").attached?
50         send(:"#{name}_attacher").send(:activerecord_after_destroy)
51       end
52     end
53   end
54 
55   # reload the attacher on record reload
56   define_method :reload do |*args|
57     result = super(*args)
58     send(:"#{name}_attacher").reload if instance_variable_defined?(:"@#{name}_attacher")
59     result
60   end
61 end