Module: Refile::Attachment::MultipleAttachments Private

Defined in:
lib/refile/attachment/multiple_attachments.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Builds a module to be used by “accepts_attachments_for”

Class Method Summary collapse

Class Method Details

.new(collection_name, collection_class:, name:, attachment:, append:, &block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



7
8
9
10
11
12
13
14
15
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
47
48
49
50
51
# File 'lib/refile/attachment/multiple_attachments.rb', line 7

def self.new(collection_name, collection_class:, name:, attachment:, append:, &block)
  Module.new do
    define_method :"#{name}_attachment_definition" do
      collection_class.send("#{attachment}_attachment_definition")
    end

    define_method :"#{name}_data" do
      collection = send(collection_name)

      all_attachers_valid = collection.all? do |record|
        record.send("#{attachment}_attacher").valid?
      end

      collection.map(&:"#{attachment}_data") if all_attachers_valid
    end

    define_method :"#{name}" do
      send(collection_name).map(&attachment)
    end

    define_method :"#{name}=" do |files|
      cache, files = [files].flatten.partition { |file| file.is_a?(String) }
      cache = Refile.parse_json(cache.first) || []
      cache = cache.reject(&:empty?)
      files = files.compact

      if not append and (!files.empty? or !cache.empty?)
        send("#{collection_name}=", [])
      end

      collection = send(collection_name)

      if files.empty? and !cache.empty?
        cache.each do |file|
          collection << collection_class.new(attachment => file.to_json)
        end
      else
        files.each do |file|
          collection << collection_class.new(attachment => file)
        end
      end
    end
    module_eval(&block) if block_given?
  end
end