jmcnevin-paperclip 2.4.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (71) hide show
  1. data/LICENSE +26 -0
  2. data/README.md +414 -0
  3. data/Rakefile +86 -0
  4. data/generators/paperclip/USAGE +5 -0
  5. data/generators/paperclip/paperclip_generator.rb +27 -0
  6. data/generators/paperclip/templates/paperclip_migration.rb.erb +19 -0
  7. data/init.rb +4 -0
  8. data/lib/generators/paperclip/USAGE +8 -0
  9. data/lib/generators/paperclip/paperclip_generator.rb +33 -0
  10. data/lib/generators/paperclip/templates/paperclip_migration.rb.erb +19 -0
  11. data/lib/paperclip.rb +480 -0
  12. data/lib/paperclip/attachment.rb +520 -0
  13. data/lib/paperclip/callback_compatibility.rb +61 -0
  14. data/lib/paperclip/geometry.rb +155 -0
  15. data/lib/paperclip/interpolations.rb +171 -0
  16. data/lib/paperclip/iostream.rb +45 -0
  17. data/lib/paperclip/matchers.rb +33 -0
  18. data/lib/paperclip/matchers/have_attached_file_matcher.rb +57 -0
  19. data/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb +81 -0
  20. data/lib/paperclip/matchers/validate_attachment_presence_matcher.rb +54 -0
  21. data/lib/paperclip/matchers/validate_attachment_size_matcher.rb +95 -0
  22. data/lib/paperclip/missing_attachment_styles.rb +87 -0
  23. data/lib/paperclip/options.rb +78 -0
  24. data/lib/paperclip/processor.rb +58 -0
  25. data/lib/paperclip/railtie.rb +26 -0
  26. data/lib/paperclip/storage.rb +3 -0
  27. data/lib/paperclip/storage/filesystem.rb +81 -0
  28. data/lib/paperclip/storage/fog.rb +163 -0
  29. data/lib/paperclip/storage/s3.rb +270 -0
  30. data/lib/paperclip/style.rb +95 -0
  31. data/lib/paperclip/thumbnail.rb +105 -0
  32. data/lib/paperclip/upfile.rb +62 -0
  33. data/lib/paperclip/version.rb +3 -0
  34. data/lib/tasks/paperclip.rake +101 -0
  35. data/rails/init.rb +2 -0
  36. data/shoulda_macros/paperclip.rb +124 -0
  37. data/test/attachment_test.rb +1161 -0
  38. data/test/database.yml +4 -0
  39. data/test/fixtures/12k.png +0 -0
  40. data/test/fixtures/50x50.png +0 -0
  41. data/test/fixtures/5k.png +0 -0
  42. data/test/fixtures/animated.gif +0 -0
  43. data/test/fixtures/bad.png +1 -0
  44. data/test/fixtures/double spaces in name.png +0 -0
  45. data/test/fixtures/fog.yml +8 -0
  46. data/test/fixtures/s3.yml +8 -0
  47. data/test/fixtures/spaced file.png +0 -0
  48. data/test/fixtures/text.txt +1 -0
  49. data/test/fixtures/twopage.pdf +0 -0
  50. data/test/fixtures/uppercase.PNG +0 -0
  51. data/test/fog_test.rb +192 -0
  52. data/test/geometry_test.rb +206 -0
  53. data/test/helper.rb +158 -0
  54. data/test/integration_test.rb +781 -0
  55. data/test/interpolations_test.rb +202 -0
  56. data/test/iostream_test.rb +71 -0
  57. data/test/matchers/have_attached_file_matcher_test.rb +24 -0
  58. data/test/matchers/validate_attachment_content_type_matcher_test.rb +87 -0
  59. data/test/matchers/validate_attachment_presence_matcher_test.rb +26 -0
  60. data/test/matchers/validate_attachment_size_matcher_test.rb +51 -0
  61. data/test/options_test.rb +75 -0
  62. data/test/paperclip_missing_attachment_styles_test.rb +80 -0
  63. data/test/paperclip_test.rb +340 -0
  64. data/test/processor_test.rb +10 -0
  65. data/test/storage/filesystem_test.rb +56 -0
  66. data/test/storage/s3_live_test.rb +88 -0
  67. data/test/storage/s3_test.rb +689 -0
  68. data/test/style_test.rb +180 -0
  69. data/test/thumbnail_test.rb +383 -0
  70. data/test/upfile_test.rb +53 -0
  71. metadata +294 -0
@@ -0,0 +1,58 @@
1
+ module Paperclip
2
+ # Paperclip processors allow you to modify attached files when they are
3
+ # attached in any way you are able. Paperclip itself uses command-line
4
+ # programs for its included Thumbnail processor, but custom processors
5
+ # are not required to follow suit.
6
+ #
7
+ # Processors are required to be defined inside the Paperclip module and
8
+ # are also required to be a subclass of Paperclip::Processor. There is
9
+ # only one method you *must* implement to properly be a subclass:
10
+ # #make, but #initialize may also be of use. Both methods accept 3
11
+ # arguments: the file that will be operated on (which is an instance of
12
+ # File), a hash of options that were defined in has_attached_file's
13
+ # style hash, and the Paperclip::Attachment itself.
14
+ #
15
+ # All #make needs to return is an instance of File (Tempfile is
16
+ # acceptable) which contains the results of the processing.
17
+ #
18
+ # See Paperclip.run for more information about using command-line
19
+ # utilities from within Processors.
20
+ class Processor
21
+ attr_accessor :file, :options, :attachment
22
+
23
+ def initialize file, options = {}, attachment = nil
24
+ @file = file
25
+ @options = options
26
+ @attachment = attachment
27
+ end
28
+
29
+ def make
30
+ end
31
+
32
+ def self.make file, options = {}, attachment = nil
33
+ new(file, options, attachment).make
34
+ end
35
+ end
36
+
37
+ # Due to how ImageMagick handles its image format conversion and how Tempfile
38
+ # handles its naming scheme, it is necessary to override how Tempfile makes
39
+ # its names so as to allow for file extensions. Idea taken from the comments
40
+ # on this blog post:
41
+ # http://marsorange.com/archives/of-mogrify-ruby-tempfile-dynamic-class-definitions
42
+ class Tempfile < ::Tempfile
43
+ # This is Ruby 1.8.7's implementation.
44
+ if RUBY_VERSION <= "1.8.6" || RUBY_PLATFORM =~ /java/
45
+ def make_tmpname(basename, n)
46
+ case basename
47
+ when Array
48
+ prefix, suffix = *basename
49
+ else
50
+ prefix, suffix = basename, ''
51
+ end
52
+
53
+ t = Time.now.strftime("%y%m%d")
54
+ path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}-#{n}#{suffix}"
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,26 @@
1
+ require 'paperclip'
2
+
3
+ module Paperclip
4
+ if defined? Rails::Railtie
5
+ require 'rails'
6
+ class Railtie < Rails::Railtie
7
+ initializer 'paperclip.insert_into_active_record' do
8
+ ActiveSupport.on_load :active_record do
9
+ Paperclip::Railtie.insert
10
+ end
11
+ end
12
+ rake_tasks do
13
+ load "tasks/paperclip.rake"
14
+ end
15
+ end
16
+ end
17
+
18
+ class Railtie
19
+ def self.insert
20
+ ActiveRecord::Base.send(:include, Paperclip::Glue)
21
+ File.send(:include, Paperclip::Upfile)
22
+
23
+ Paperclip.options[:logger] = defined?(ActiveRecord) ? ActiveRecord::Base.logger : Rails.logger
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,3 @@
1
+ require "paperclip/storage/filesystem"
2
+ require "paperclip/storage/fog"
3
+ require "paperclip/storage/s3"
@@ -0,0 +1,81 @@
1
+ module Paperclip
2
+ module Storage
3
+ # The default place to store attachments is in the filesystem. Files on the local
4
+ # filesystem can be very easily served by Apache without requiring a hit to your app.
5
+ # They also can be processed more easily after they've been saved, as they're just
6
+ # normal files. There is one Filesystem-specific option for has_attached_file.
7
+ # * +path+: The location of the repository of attachments on disk. This can (and, in
8
+ # almost all cases, should) be coordinated with the value of the +url+ option to
9
+ # allow files to be saved into a place where Apache can serve them without
10
+ # hitting your app. Defaults to
11
+ # ":rails_root/public/:attachment/:id/:style/:basename.:extension"
12
+ # By default this places the files in the app's public directory which can be served
13
+ # directly. If you are using capistrano for deployment, a good idea would be to
14
+ # make a symlink to the capistrano-created system directory from inside your app's
15
+ # public directory.
16
+ # See Paperclip::Attachment#interpolate for more information on variable interpolaton.
17
+ # :path => "/var/app/attachments/:class/:id/:style/:basename.:extension"
18
+ module Filesystem
19
+ def self.extended base
20
+ end
21
+
22
+ def exists?(style_name = default_style)
23
+ if original_filename
24
+ File.exist?(path(style_name))
25
+ else
26
+ false
27
+ end
28
+ end
29
+
30
+ # Returns representation of the data of the file assigned to the given
31
+ # style, in the format most representative of the current storage.
32
+ def to_file style_name = default_style
33
+ @queued_for_write[style_name] || (File.new(path(style_name), 'rb') if exists?(style_name))
34
+ end
35
+
36
+ def flush_writes #:nodoc:
37
+ @queued_for_write.each do |style_name, file|
38
+ file.close
39
+ FileUtils.mkdir_p(File.dirname(path(style_name)))
40
+ log("saving #{path(style_name)}")
41
+ begin
42
+ FileUtils.mv(file.path, path(style_name))
43
+ rescue SystemCallError
44
+ FileUtils.cp(file.path, path(style_name))
45
+ FileUtils.rm(file.path)
46
+ end
47
+ FileUtils.chmod(0666&~File.umask, path(style_name))
48
+ end
49
+
50
+ after_flush_writes # allows attachment to clean up temp files
51
+
52
+ @queued_for_write = {}
53
+ end
54
+
55
+ def flush_deletes #:nodoc:
56
+ @queued_for_delete.each do |path|
57
+ begin
58
+ log("deleting #{path}")
59
+ FileUtils.rm(path) if File.exist?(path)
60
+ rescue Errno::ENOENT => e
61
+ # ignore file-not-found, let everything else pass
62
+ end
63
+ begin
64
+ while(true)
65
+ path = File.dirname(path)
66
+ FileUtils.rmdir(path)
67
+ break if File.exists?(path) # Ruby 1.9.2 does not raise if the removal failed.
68
+ end
69
+ rescue Errno::EEXIST, Errno::ENOTEMPTY, Errno::ENOENT, Errno::EINVAL, Errno::ENOTDIR, Errno::EACCES
70
+ # Stop trying to remove parent directories
71
+ rescue SystemCallError => e
72
+ log("There was an unexpected error while deleting directories: #{e.class}")
73
+ # Ignore it
74
+ end
75
+ end
76
+ @queued_for_delete = []
77
+ end
78
+ end
79
+
80
+ end
81
+ end
@@ -0,0 +1,163 @@
1
+ module Paperclip
2
+ module Storage
3
+ # fog is a modern and versatile cloud computing library for Ruby.
4
+ # Among others, it supports Amazon S3 to store your files. In
5
+ # contrast to the outdated AWS-S3 gem it is actively maintained and
6
+ # supports multiple locations.
7
+ # Amazon's S3 file hosting service is a scalable, easy place to
8
+ # store files for distribution. You can find out more about it at
9
+ # http://aws.amazon.com/s3 There are a few fog-specific options for
10
+ # has_attached_file, which will be explained using S3 as an example:
11
+ # * +fog_credentials+: Takes a Hash with your credentials. For S3,
12
+ # you can use the following format:
13
+ # aws_access_key_id: '<your aws_access_key_id>'
14
+ # aws_secret_access_key: '<your aws_secret_access_key>'
15
+ # provider: 'AWS'
16
+ # region: 'eu-west-1'
17
+ # * +fog_directory+: This is the name of the S3 bucket that will
18
+ # store your files. Remember that the bucket must be unique across
19
+ # all of Amazon S3. If the bucket does not exist, Paperclip will
20
+ # attempt to create it.
21
+ # * +path+: This is the key under the bucket in which the file will
22
+ # be stored. The URL will be constructed from the bucket and the
23
+ # path. This is what you will want to interpolate. Keys should be
24
+ # unique, like filenames, and despite the fact that S3 (strictly
25
+ # speaking) does not support directories, you can still use a / to
26
+ # separate parts of your file name.
27
+ # * +fog_public+: (optional, defaults to true) Should the uploaded
28
+ # files be public or not? (true/false)
29
+ # * +fog_host+: (optional) The fully-qualified domain name (FQDN)
30
+ # that is the alias to the S3 domain of your bucket, e.g.
31
+ # 'http://images.example.com'. This can also be used in
32
+ # conjunction with Cloudfront (http://aws.amazon.com/cloudfront)
33
+
34
+ module Fog
35
+ def self.extended base
36
+ begin
37
+ require 'fog'
38
+ rescue LoadError => e
39
+ e.message << " (You may need to install the fog gem)"
40
+ raise e
41
+ end unless defined?(Fog)
42
+
43
+ base.instance_eval do
44
+ unless @options.url.to_s.match(/^:fog.*url$/)
45
+ @options.path = @options.path.gsub(/:url/, @options.url)
46
+ @options.url = ':fog_public_url'
47
+ end
48
+ Paperclip.interpolates(:fog_public_url) do |attachment, style|
49
+ attachment.public_url(style)
50
+ end unless Paperclip::Interpolations.respond_to? :fog_public_url
51
+ end
52
+ end
53
+
54
+ def exists?(style = default_style)
55
+ if original_filename
56
+ !!directory.files.head(path(style))
57
+ else
58
+ false
59
+ end
60
+ end
61
+
62
+ def fog_credentials
63
+ @fog_credentials ||= parse_credentials(@options.fog_credentials)
64
+ end
65
+
66
+ def fog_file
67
+ @fog_file ||= @options.fog_file || {}
68
+ end
69
+
70
+ def fog_public
71
+ return @fog_public if defined?(@fog_public)
72
+ @fog_public = defined?(@options.fog_public) ? @options.fog_public : true
73
+ end
74
+
75
+ def flush_writes
76
+ for style, file in @queued_for_write do
77
+ log("saving #{path(style)}")
78
+ retried = false
79
+ begin
80
+ directory.files.create(fog_file.merge(
81
+ :body => file,
82
+ :key => path(style),
83
+ :public => fog_public
84
+ ))
85
+ rescue Excon::Errors::NotFound
86
+ raise if retried
87
+ retried = true
88
+ directory.save
89
+ retry
90
+ end
91
+ end
92
+
93
+ after_flush_writes # allows attachment to clean up temp files
94
+
95
+ @queued_for_write = {}
96
+ end
97
+
98
+ def flush_deletes
99
+ for path in @queued_for_delete do
100
+ log("deleting #{path}")
101
+ directory.files.new(:key => path).destroy
102
+ end
103
+ @queued_for_delete = []
104
+ end
105
+
106
+ # Returns representation of the data of the file assigned to the given
107
+ # style, in the format most representative of the current storage.
108
+ def to_file(style = default_style)
109
+ if @queued_for_write[style]
110
+ @queued_for_write[style]
111
+ else
112
+ body = directory.files.get(path(style)).body
113
+ filename = path(style)
114
+ extname = File.extname(filename)
115
+ basename = File.basename(filename, extname)
116
+ file = Tempfile.new([basename, extname])
117
+ file.binmode
118
+ file.write(body)
119
+ file.rewind
120
+ file
121
+ end
122
+ end
123
+
124
+ def public_url(style = default_style)
125
+ if @options.fog_host
126
+ host = (@options.fog_host =~ /%d/) ? @options.fog_host % (path(style).hash % 4) : @options.fog_host
127
+ "#{host}/#{path(style)}"
128
+ else
129
+ directory.files.new(:key => path(style)).public_url
130
+ end
131
+ end
132
+
133
+ def parse_credentials(creds)
134
+ creds = find_credentials(creds).stringify_keys
135
+ env = Object.const_defined?(:Rails) ? Rails.env : nil
136
+ (creds[env] || creds).symbolize_keys
137
+ end
138
+
139
+ private
140
+
141
+ def find_credentials(creds)
142
+ case creds
143
+ when File
144
+ YAML::load(ERB.new(File.read(creds.path)).result)
145
+ when String, Pathname
146
+ YAML::load(ERB.new(File.read(creds)).result)
147
+ when Hash
148
+ creds
149
+ else
150
+ raise ArgumentError, "Credentials are not a path, file, or hash."
151
+ end
152
+ end
153
+
154
+ def connection
155
+ @connection ||= ::Fog::Storage.new(fog_credentials)
156
+ end
157
+
158
+ def directory
159
+ @directory ||= connection.directories.new(:key => @options.fog_directory)
160
+ end
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,270 @@
1
+ module Paperclip
2
+ module Storage
3
+ # Amazon's S3 file hosting service is a scalable, easy place to store files for
4
+ # distribution. You can find out more about it at http://aws.amazon.com/s3
5
+ # There are a few S3-specific options for has_attached_file:
6
+ # * +s3_credentials+: Takes a path, a File, or a Hash. The path (or File) must point
7
+ # to a YAML file containing the +access_key_id+ and +secret_access_key+ that Amazon
8
+ # gives you. You can 'environment-space' this just like you do to your
9
+ # database.yml file, so different environments can use different accounts:
10
+ # development:
11
+ # access_key_id: 123...
12
+ # secret_access_key: 123...
13
+ # test:
14
+ # access_key_id: abc...
15
+ # secret_access_key: abc...
16
+ # production:
17
+ # access_key_id: 456...
18
+ # secret_access_key: 456...
19
+ # This is not required, however, and the file may simply look like this:
20
+ # access_key_id: 456...
21
+ # secret_access_key: 456...
22
+ # In which case, those access keys will be used in all environments. You can also
23
+ # put your bucket name in this file, instead of adding it to the code directly.
24
+ # This is useful when you want the same account but a different bucket for
25
+ # development versus production.
26
+ # * +s3_permissions+: This is a String that should be one of the "canned" access
27
+ # policies that S3 provides (more information can be found here:
28
+ # http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAccessPolicy.html)
29
+ # The default for Paperclip is :public_read.
30
+ #
31
+ # You can set permission on a per style bases by doing the following:
32
+ # :s3_permissions => {
33
+ # :original => :private
34
+ # }
35
+ # Or globaly:
36
+ # :s3_permissions => :private
37
+ #
38
+ # * +s3_protocol+: The protocol for the URLs generated to your S3 assets. Can be either
39
+ # 'http' or 'https'. Defaults to 'http' when your :s3_permissions are :public_read (the
40
+ # default), and 'https' when your :s3_permissions are anything else.
41
+ # * +s3_headers+: A hash of headers such as {'Expires' => 1.year.from_now.httpdate}
42
+ # * +bucket+: This is the name of the S3 bucket that will store your files. Remember
43
+ # that the bucket must be unique across all of Amazon S3. If the bucket does not exist
44
+ # Paperclip will attempt to create it. The bucket name will not be interpolated.
45
+ # You can define the bucket as a Proc if you want to determine it's name at runtime.
46
+ # Paperclip will call that Proc with attachment as the only argument.
47
+ # * +s3_host_alias+: The fully-qualified domain name (FQDN) that is the alias to the
48
+ # S3 domain of your bucket. Used with the :s3_alias_url url interpolation. See the
49
+ # link in the +url+ entry for more information about S3 domains and buckets.
50
+ # * +url+: There are four options for the S3 url. You can choose to have the bucket's name
51
+ # placed domain-style (bucket.s3.amazonaws.com) or path-style (s3.amazonaws.com/bucket).
52
+ # You can also specify a CNAME (which requires the CNAME to be specified as
53
+ # :s3_alias_url. You can read more about CNAMEs and S3 at
54
+ # http://docs.amazonwebservices.com/AmazonS3/latest/index.html?VirtualHosting.html
55
+ # Normally, this won't matter in the slightest and you can leave the default (which is
56
+ # path-style, or :s3_path_url). But in some cases paths don't work and you need to use
57
+ # the domain-style (:s3_domain_url). Anything else here will be treated like path-style.
58
+ # NOTE: If you use a CNAME for use with CloudFront, you can NOT specify https as your
59
+ # :s3_protocol; This is *not supported* by S3/CloudFront. Finally, when using the host
60
+ # alias, the :bucket parameter is ignored, as the hostname is used as the bucket name
61
+ # by S3. The fourth option for the S3 url is :asset_host, which uses Rails' built-in
62
+ # asset_host settings. NOTE: To get the full url from a paperclip'd object, use the
63
+ # image_path helper; this is what image_tag uses to generate the url for an img tag.
64
+ # * +path+: This is the key under the bucket in which the file will be stored. The
65
+ # URL will be constructed from the bucket and the path. This is what you will want
66
+ # to interpolate. Keys should be unique, like filenames, and despite the fact that
67
+ # S3 (strictly speaking) does not support directories, you can still use a / to
68
+ # separate parts of your file name.
69
+ # * +s3_host_name+: If you are using your bucket in Tokyo region etc, write host_name.
70
+ module S3
71
+ def self.extended base
72
+ begin
73
+ require 'aws/s3'
74
+ rescue LoadError => e
75
+ e.message << " (You may need to install the aws-s3 gem)"
76
+ raise e
77
+ end unless defined?(AWS::S3)
78
+
79
+ base.instance_eval do
80
+ @s3_options = @options.s3_options || {}
81
+ @s3_permissions = set_permissions(@options.s3_permissions)
82
+ @s3_protocol = @options.s3_protocol ||
83
+ Proc.new do |style, attachment|
84
+ permission = (@s3_permissions[style.to_sym] || @s3_permissions[:default])
85
+ permission = permission.call(attachment, style) if permission.is_a?(Proc)
86
+ (permission == :public_read) ? 'http' : 'https'
87
+ end
88
+ @s3_headers = @options.s3_headers || {}
89
+
90
+ unless @options.url.to_s.match(/^:s3.*url$/) || @options.url == ":asset_host"
91
+ @options.path = @options.path.gsub(/:url/, @options.url).gsub(/^:rails_root\/public\/system/, '')
92
+ @options.url = ":s3_path_url"
93
+ end
94
+ @options.url = @options.url.inspect if @options.url.is_a?(Symbol)
95
+
96
+ @http_proxy = @options.http_proxy || nil
97
+ if @http_proxy
98
+ @s3_options.merge!({:proxy => @http_proxy})
99
+ end
100
+
101
+ AWS::S3::Base.establish_connection!( @s3_options.merge(
102
+ :access_key_id => s3_credentials[:access_key_id],
103
+ :secret_access_key => s3_credentials[:secret_access_key]
104
+ ))
105
+ end
106
+ Paperclip.interpolates(:s3_alias_url) do |attachment, style|
107
+ "#{attachment.s3_protocol(style)}://#{attachment.s3_host_alias}/#{attachment.path(style).gsub(%r{^/}, "")}"
108
+ end unless Paperclip::Interpolations.respond_to? :s3_alias_url
109
+ Paperclip.interpolates(:s3_path_url) do |attachment, style|
110
+ "#{attachment.s3_protocol(style)}://#{attachment.s3_host_name}/#{attachment.bucket_name}/#{attachment.path(style).gsub(%r{^/}, "")}"
111
+ end unless Paperclip::Interpolations.respond_to? :s3_path_url
112
+ Paperclip.interpolates(:s3_domain_url) do |attachment, style|
113
+ "#{attachment.s3_protocol(style)}://#{attachment.bucket_name}.#{attachment.s3_host_name}/#{attachment.path(style).gsub(%r{^/}, "")}"
114
+ end unless Paperclip::Interpolations.respond_to? :s3_domain_url
115
+ Paperclip.interpolates(:asset_host) do |attachment, style|
116
+ "#{attachment.path(style).gsub(%r{^/}, "")}"
117
+ end unless Paperclip::Interpolations.respond_to? :asset_host
118
+ end
119
+
120
+ def expiring_url(time = 3600, style_name = default_style)
121
+ AWS::S3::S3Object.url_for(path(style_name), bucket_name, :expires_in => time, :use_ssl => (s3_protocol(style_name) == 'https'))
122
+ end
123
+
124
+ def s3_credentials
125
+ @s3_credentials ||= parse_credentials(@options.s3_credentials)
126
+ end
127
+
128
+ def s3_host_name
129
+ @options.s3_host_name || s3_credentials[:s3_host_name] || "s3.amazonaws.com"
130
+ end
131
+
132
+ def s3_host_alias
133
+ @s3_host_alias = @options.s3_host_alias
134
+ @s3_host_alias = @s3_host_alias.call(self) if @s3_host_alias.is_a?(Proc)
135
+ @s3_host_alias
136
+ end
137
+
138
+ def bucket_name
139
+ @bucket = @options.bucket || s3_credentials[:bucket]
140
+ @bucket = @bucket.call(self) if @bucket.is_a?(Proc)
141
+ @bucket
142
+ end
143
+
144
+ def using_http_proxy?
145
+ !!@http_proxy
146
+ end
147
+
148
+ def http_proxy_host
149
+ using_http_proxy? ? @http_proxy[:host] : nil
150
+ end
151
+
152
+ def http_proxy_port
153
+ using_http_proxy? ? @http_proxy[:port] : nil
154
+ end
155
+
156
+ def http_proxy_user
157
+ using_http_proxy? ? @http_proxy[:user] : nil
158
+ end
159
+
160
+ def http_proxy_password
161
+ using_http_proxy? ? @http_proxy[:password] : nil
162
+ end
163
+
164
+ def set_permissions permissions
165
+ if permissions.is_a?(Hash)
166
+ permissions[:default] = permissions[:default] || :public_read
167
+ else
168
+ permissions = { :default => permissions || :public_read }
169
+ end
170
+ permissions
171
+ end
172
+
173
+ def parse_credentials creds
174
+ creds = find_credentials(creds).stringify_keys
175
+ env = Object.const_defined?(:Rails) ? Rails.env : nil
176
+ (creds[env] || creds).symbolize_keys
177
+ end
178
+
179
+ def exists?(style = default_style)
180
+ if original_filename
181
+ AWS::S3::S3Object.exists?(path(style), bucket_name)
182
+ else
183
+ false
184
+ end
185
+ end
186
+
187
+ def s3_permissions(style = default_style)
188
+ s3_permissions = @s3_permissions[style] || @s3_permissions[:default]
189
+ s3_permissions = s3_permissions.call(self, style) if s3_permissions.is_a?(Proc)
190
+ s3_permissions
191
+ end
192
+
193
+ def s3_protocol(style = default_style)
194
+ if @s3_protocol.is_a?(Proc)
195
+ @s3_protocol.call(style, self)
196
+ else
197
+ @s3_protocol
198
+ end
199
+ end
200
+
201
+ # Returns representation of the data of the file assigned to the given
202
+ # style, in the format most representative of the current storage.
203
+ def to_file style = default_style
204
+ return @queued_for_write[style] if @queued_for_write[style]
205
+ filename = path(style)
206
+ extname = File.extname(filename)
207
+ basename = File.basename(filename, extname)
208
+ file = Tempfile.new([basename, extname])
209
+ file.binmode
210
+ file.write(AWS::S3::S3Object.value(path(style), bucket_name))
211
+ file.rewind
212
+ return file
213
+ end
214
+
215
+ def create_bucket
216
+ AWS::S3::Bucket.create(bucket_name)
217
+ end
218
+
219
+ def flush_writes #:nodoc:
220
+ @queued_for_write.each do |style, file|
221
+ begin
222
+ log("saving #{path(style)}")
223
+ AWS::S3::S3Object.store(path(style),
224
+ file,
225
+ bucket_name,
226
+ {:content_type => file.content_type.to_s.strip,
227
+ :access => s3_permissions(style),
228
+ }.merge(@s3_headers))
229
+ rescue AWS::S3::NoSuchBucket => e
230
+ create_bucket
231
+ retry
232
+ rescue AWS::S3::ResponseError => e
233
+ raise
234
+ end
235
+ end
236
+
237
+ after_flush_writes # allows attachment to clean up temp files
238
+
239
+ @queued_for_write = {}
240
+ end
241
+
242
+ def flush_deletes #:nodoc:
243
+ @queued_for_delete.each do |path|
244
+ begin
245
+ log("deleting #{path}")
246
+ AWS::S3::S3Object.delete(path, bucket_name)
247
+ rescue AWS::S3::ResponseError
248
+ # Ignore this.
249
+ end
250
+ end
251
+ @queued_for_delete = []
252
+ end
253
+
254
+ def find_credentials creds
255
+ case creds
256
+ when File
257
+ YAML::load(ERB.new(File.read(creds.path)).result)
258
+ when String, Pathname
259
+ YAML::load(ERB.new(File.read(creds)).result)
260
+ when Hash
261
+ creds
262
+ else
263
+ raise ArgumentError, "Credentials are not a path, file, or hash."
264
+ end
265
+ end
266
+ private :find_credentials
267
+
268
+ end
269
+ end
270
+ end