Module: Shrine::Plugins::Sequel::AttachmentMethods

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

Instance Method Summary collapse

Instance Method Details

#included(model) ⇒ Object



17
18
19
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
# File 'lib/shrine/plugins/sequel.rb', line 17

def included(model)
  super

  return unless model < ::Sequel::Model

  name = attachment_name

  if shrine_class.opts[:sequel_validations]
    define_method :validate do
      super()
      send(:"#{name}_attacher").errors.each do |message|
        errors.add(name, *message)
      end
    end
  end

  if shrine_class.opts[:sequel_callbacks]
    define_method :before_save do
      super()
      attacher = send(:"#{name}_attacher")
      attacher.save if attacher.changed?
    end

    define_method :after_save do
      super()
      attacher = send(:"#{name}_attacher")
      db.after_commit { attacher.finalize } if attacher.changed?
    end

    define_method :after_destroy do
      super()
      attacher = send(:"#{name}_attacher")
      db.after_commit { attacher.destroy } if attacher.read
    end
  end
end