1
+ module S3UpNow
2
+ module Paperclip
3
+ def self . included ( base )
4
+ base . extend ClassMethods
5
+ base . class_eval do
6
+ private
7
+
8
+ def s3_upnow_attachment ( name )
9
+ send ( name )
10
+ end
11
+
12
+ def s3_upnow_destination_bucket ( name )
13
+ s3_upnow_attachment ( name ) . options [ :bucket ] . call
14
+ end
15
+
16
+ def s3_upnow_destination_path ( name )
17
+ s3_upnow_attachment ( name ) . path [ 1 ..-1 ]
18
+ end
19
+
20
+ def s3_upnow_destination_permissions ( name )
21
+ s3_upnow_attachment ( name ) . s3_permissions
22
+ end
23
+ end
24
+ end
25
+ end
26
+
27
+ module ClassMethods
28
+ def has_attached_file ( name , options = { } )
29
+ puts "here"
30
+ self . class_eval do
31
+ attr_accessor "#{ name } _s3_key"
32
+
33
+ before_validation "s3_upnow_copy_metadata_from_#{ name } " . to_sym , unless : "#{ name } _s3_key.blank?"
34
+ after_save "s3_upnow_copy_file_from_#{ name } " . to_sym , unless : "#{ name } _s3_key.blank?"
35
+
36
+ private
37
+
38
+ define_method "s3_upnow_copy_metadata_from_#{ name } " do
39
+ s3 = AWS ::S3 . new
40
+ s3_head = s3 . buckets [ S3UpNow . config . bucket ] . objects [ instance_variable_get ( "@#{ name } _s3_key" ) ] . head
41
+
42
+ s3_upnow_attachment ( name ) . clear
43
+ self . send "#{ name } _file_name=" , File . basename ( instance_variable_get ( "@#{ name } _s3_key" ) )
44
+ self . send "#{ name } _file_size=" , s3_head . content_length
45
+ self . send "#{ name } _content_type=" , s3_head . content_type
46
+ self . send "#{ name } _updated_at=" , s3_head . last_modified
47
+ end
48
+
49
+ define_method "s3_upnow_copy_file_from_#{ name } " do
50
+ s3 = AWS ::S3 . new
51
+ orig_bucket = s3 . buckets [ S3UpNow . config . bucket ]
52
+ orig_object = orig_bucket . objects [ instance_variable_get ( "@#{ name } _s3_key" ) ]
53
+ dest_bucket = s3 . buckets [ s3_upnow_destination_bucket ( name ) ]
54
+ dest_object = dest_bucket . objects [ s3_upnow_destination_path ( name ) ]
55
+ dest_object . copy_from ( orig_object , acl : s3_upnow_destination_permissions ( name ) )
56
+ end
57
+ end
58
+ super ( name , options )
59
+ end
60
+ end
61
+ end
0 commit comments