Module: Attachable

Extended by:
ActiveSupport::Concern
Defined in:
lib/generators/cm_admin/templates/concerns/attachable.rb

Instance Method Summary collapse

Instance Method Details

#attached_url(attachment_type) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/generators/cm_admin/templates/concerns/attachable.rb', line 48

def attached_url(attachment_type)
  if send(attachment_type.to_s).attached? && send(attachment_type.to_s).class == ActiveStorage::Attached::One
    Rails.application.routes.url_helpers.rails_blob_url(send(attachment_type.to_s))
  elsif send(attachment_type.to_s).attached? && send(attachment_type.to_s).class == ActiveStorage::Attached::Many
    send(attachment_type.to_s)
  end
end

#initialize(args) ⇒ Object



18
19
20
21
# File 'lib/generators/cm_admin/templates/concerns/attachable.rb', line 18

def initialize(args)
  add_accessors_for_attachment_types
  super
end

#save_attachmentObject



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 'lib/generators/cm_admin/templates/concerns/attachable.rb', line 23

def save_attachment
  self.class.attachment_types.each do |attachment_type|
    next if send("#{attachment_type}_file").blank?

    arr = []
    if send("#{attachment_type}_file").class.eql?(Array)
      arr = send("#{attachment_type}_file")
    else
      arr << send("#{attachment_type}_file")
    end
    arr.each do |x|
      regexp = %r{\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)}m
      data_uri_parts = x[:content].match(regexp) || []
      decoded_data = Base64.decode64(data_uri_parts[2])
      filename = x[:filename]
      filepath = "#{Rails.root}/tmp/#{filename}"
      File.open(filepath, 'wb') do |f|
        f.write(decoded_data)
      end
      send(attachment_type.to_s).attach(io: File.open(filepath), filename: filename, content_type: data_uri_parts[1])
      File.delete(filepath)
    end
  end
end

#save_with_attachmentsObject



7
8
9
10
# File 'lib/generators/cm_admin/templates/concerns/attachable.rb', line 7

def save_with_attachments
  save!
  save_attachment
end

#update!(args) ⇒ Object



12
13
14
15
16
# File 'lib/generators/cm_admin/templates/concerns/attachable.rb', line 12

def update!(args)
  add_accessors_for_attachment_types
  super
  save_attachment
end