Module: S3UpNow::ClassMethods

Defined in:
lib/s3-upnow/paperclip.rb

Instance Method Summary collapse

Instance Method Details

#has_attached_file(name, options = {}) ⇒ Object



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
57
58
59
# File 'lib/s3-upnow/paperclip.rb', line 28

def has_attached_file(name, options = {})
  puts "here"
  self.class_eval do
    attr_accessor "#{name}_s3_key"

    before_validation "s3_upnow_copy_metadata_from_#{name}".to_sym, unless: "#{name}_s3_key.blank?"
    after_save "s3_upnow_copy_file_from_#{name}".to_sym, unless: "#{name}_s3_key.blank?"

    private

    define_method "s3_upnow_copy_metadata_from_#{name}" do
      s3 = AWS::S3.new
      s3_head = s3.buckets[S3UpNow.config.bucket].objects[instance_variable_get("@#{name}_s3_key")].head

      s3_upnow_attachment(name).clear
      self.send "#{name}_file_name=", File.basename(instance_variable_get("@#{name}_s3_key"))
      self.send "#{name}_file_size=", s3_head.content_length
      self.send "#{name}_content_type=", s3_head.content_type
      self.send "#{name}_updated_at=", s3_head.last_modified 
    end

    define_method "s3_upnow_copy_file_from_#{name}" do
      s3 = AWS::S3.new
      orig_bucket = s3.buckets[S3UpNow.config.bucket]
      orig_object = orig_bucket.objects[instance_variable_get("@#{name}_s3_key")]
      dest_bucket = s3.buckets[s3_upnow_destination_bucket(name)]
      dest_object = dest_bucket.objects[s3_upnow_destination_path(name)]
      dest_object.copy_from(orig_object, acl: s3_upnow_destination_permissions(name))
    end
  end
  super(name, options)
end