Module: Models::DragonflyAccessor::ClassMethods

Defined in:
app/concerns/models/dragonfly_accessor.rb

Overview

ActiveSupport::Concern mixin: class methods.

Instance Method Summary collapse

Instance Method Details

#dragonfly_accessor(attribute, opts = {}, &config_block) ⇒ Object



16
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
# File 'app/concerns/models/dragonfly_accessor.rb', line 16

def dragonfly_accessor(attribute, opts = {}, &config_block)
  super do
    config_block&.call

    mime_attribute = :"#{attribute}_mime_type" if opts.delete(:mime_type)

    after_assign do |attachment|
      attrs = { "#{attribute}_name": FileNamingHelper.sanitize_file_name(attachment.name) }
      attrs[mime_attribute] = attachment.mime_type if mime_attribute
      assign_attributes(attrs)
    end

    after_unassign do |_attachment|
      assign_attributes(mime_attribute => nil) if mime_attribute
    end

    storage_options do |a|
      # S3DataStore exposes a private `generate_uid` that produces our
      # canonical path. The local FileDataStore (used in tests) doesn't,
      # so fall back to a SecureRandom-derived path that follows the same
      # `<basename>/<rand>/<name>` shape.
      path =
        if a.app.datastore.respond_to?(:generate_uid, true)
          a.app.datastore.send(:generate_uid, a.name || "file")
        else
          "#{a.name || 'file'}/#{SecureRandom.hex(16)}"
        end
      { path: path }
    end
  end
end