Module: Shrine::Plugins::Activerecord::AttachmentMethods

Defined in:
lib/shrine/plugins/activerecord.rb

Instance Method Summary collapse

Instance Method Details

#included(model) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/shrine/plugins/activerecord.rb', line 20

def included(model)
  super

  return unless model < ::ActiveRecord::Base

  name = @name

  if shrine_class.opts[:activerecord][:validations]
    model.validate do
      send(:"#{name}_attacher").send(:activerecord_validate)
    end
  end

  if shrine_class.opts[:activerecord][:callbacks]
    model.before_save do
      if send(:"#{name}_attacher").changed?
        send(:"#{name}_attacher").send(:activerecord_before_save)
      end
    end

    [:create, :update].each do |action|
      model.after_commit on: action do
        if send(:"#{name}_attacher").changed?
          send(:"#{name}_attacher").send(:activerecord_after_save)
        end
      end
    end

    model.after_commit on: :destroy do
      if send(:"#{name}_attacher").attached?
        send(:"#{name}_attacher").send(:activerecord_after_destroy)
      end
    end
  end

  # reload the attacher on record reload
  define_method :reload do |*args|
    result = super(*args)
    instance_variable_set(:"@#{name}_attacher", nil)
    result
  end
end