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) ⇒ void

This method returns an undefined value.

Declare a Dragonfly attachment accessor with mime-type caching and
datastore-compatible file naming.

Parameters:

  • attribute (Symbol)

    name of the attachment attribute

  • opts (Hash) (defaults to: {})

    accessor options (all other keys are forwarded to
    Dragonfly's dragonfly_accessor)

  • config_block (Proc)

    optional Dragonfly configuration block

Options Hash (opts):

  • mime_type (Boolean)

    cache the attachment's mime type in a
    <attribute>_mime_type column on assign



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

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