thoughtbot-paperclip 2.1.5

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,26 @@
1
+
2
+ LICENSE
3
+
4
+ The MIT License
5
+
6
+ Copyright (c) 2008 Jon Yurek and thoughtbot, inc.
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in
16
+ all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ THE SOFTWARE.
25
+
26
+
@@ -0,0 +1,59 @@
1
+ =Paperclip
2
+
3
+ Paperclip is intended as an easy file attachment library for ActiveRecord. The intent behind it was to keep setup as easy as possible and to treat files as much like other attributes as possible. This means they aren't saved to their final locations on disk, nor are they deleted if set to nil, until ActiveRecord::Base#save is called. It manages validations based on size and presence, if required. It can transform its assigned image into thumbnails if needed, and the prerequisites are as simple as installing ImageMagick (which, for most modern Unix-based systems, is as easy as installing the right packages). Attached files are saved to the filesystem and referenced in the browser by an easily understandable specification, which has sensible and useful defaults.
4
+
5
+ See the documentation for the +has_attached_file+ method for options.
6
+
7
+ ==Usage
8
+
9
+ In your model:
10
+
11
+ class User < ActiveRecord::Base
12
+ has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
13
+ end
14
+
15
+ In your migrations:
16
+
17
+ class AddAvatarColumnsToUser < ActiveRecord::Migration
18
+ def self.up
19
+ add_column :users, :avatar_file_name, :string
20
+ add_column :users, :avatar_content_type, :string
21
+ add_column :users, :avatar_file_size, :integer
22
+ add_column :users, :avatar_updated_at, :datetime
23
+ end
24
+
25
+ def self.down
26
+ remove_column :users, :avatar_file_name
27
+ remove_column :users, :avatar_content_type
28
+ remove_column :users, :avatar_file_size
29
+ remove_column :users, :avatar_updated_at
30
+ end
31
+ end
32
+
33
+ In your edit and new views:
34
+
35
+ <% form_for :user, @user, :url => user_path, :html => { :multipart => true } do |form| %>
36
+ <%= form.file_field :avatar %>
37
+ <% end %>
38
+
39
+ In your controller:
40
+
41
+ def create
42
+ @user = User.create( params[:user] )
43
+ end
44
+
45
+ In your show view:
46
+
47
+ <%= image_tag @user.avatar.url %>
48
+ <%= image_tag @user.avatar.url(:medium) %>
49
+ <%= image_tag @user.avatar.url(:thumb) %>
50
+
51
+ ==Contributing
52
+
53
+ If you'd like to contribute a feature or bugfix, thanks! To make sure your fix/feature
54
+ has a high chance of being added, please read the following guidelines:
55
+
56
+ 1. Ask on the mailing list, or post a ticket in Lighthouse.
57
+ 2. Make sure there are tests! I will not accept any patch that is not tested.
58
+ It's a rare time when explicit tests aren't needed. If you have questions about
59
+ writing tests for paperclip, please ask the mailing list.
@@ -0,0 +1,94 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+ require 'rake/gempackagetask'
5
+
6
+ $LOAD_PATH << File.join(File.dirname(__FILE__), 'lib')
7
+ require 'paperclip'
8
+
9
+ desc 'Default: run unit tests.'
10
+ task :default => [:clean, :test]
11
+
12
+ desc 'Test the paperclip plugin.'
13
+ Rake::TestTask.new(:test) do |t|
14
+ t.libs << 'lib' << 'profile'
15
+ t.pattern = 'test/**/*_test.rb'
16
+ t.verbose = true
17
+ end
18
+
19
+ desc 'Start an IRB session with all necessary files required.'
20
+ task :shell do |t|
21
+ chdir File.dirname(__FILE__)
22
+ exec 'irb -I lib/ -I lib/paperclip -r rubygems -r active_record -r tempfile -r init'
23
+ end
24
+
25
+ desc 'Generate documentation for the paperclip plugin.'
26
+ Rake::RDocTask.new(:rdoc) do |rdoc|
27
+ rdoc.rdoc_dir = 'doc'
28
+ rdoc.title = 'Paperclip'
29
+ rdoc.options << '--line-numbers' << '--inline-source'
30
+ rdoc.rdoc_files.include('README')
31
+ rdoc.rdoc_files.include('lib/**/*.rb')
32
+ end
33
+
34
+ desc 'Update documentation on website'
35
+ task :sync_docs => 'rdoc' do
36
+ `rsync -ave ssh doc/ dev@dev.thoughtbot.com:/home/dev/www/dev.thoughtbot.com/paperclip`
37
+ end
38
+
39
+ desc 'Clean up files.'
40
+ task :clean do |t|
41
+ FileUtils.rm_rf "doc"
42
+ FileUtils.rm_rf "tmp"
43
+ FileUtils.rm_rf "pkg"
44
+ FileUtils.rm "test/debug.log" rescue nil
45
+ FileUtils.rm "test/paperclip.db" rescue nil
46
+ end
47
+
48
+ spec = Gem::Specification.new do |s|
49
+ s.name = "paperclip"
50
+ s.version = Paperclip::VERSION
51
+ s.author = "Jon Yurek"
52
+ s.email = "jyurek@thoughtbot.com"
53
+ s.homepage = "http://www.thoughtbot.com/projects/paperclip"
54
+ s.platform = Gem::Platform::RUBY
55
+ s.summary = "File attachments as attributes for ActiveRecord"
56
+ s.files = FileList["README*",
57
+ "LICENSE",
58
+ "Rakefile",
59
+ "init.rb",
60
+ "{generators,lib,tasks,test,shoulda_macros}/**/*"].to_a
61
+ s.require_path = "lib"
62
+ s.test_files = FileList["test/**/test_*.rb"].to_a
63
+ s.rubyforge_project = "paperclip"
64
+ s.has_rdoc = true
65
+ s.extra_rdoc_files = FileList["README*"].to_a
66
+ s.rdoc_options << '--line-numbers' << '--inline-source'
67
+ s.requirements << "ImageMagick"
68
+ s.add_runtime_dependency 'right_aws'
69
+ s.add_development_dependency 'thoughtbot-shoulda'
70
+ s.add_development_dependency 'mocha'
71
+ end
72
+
73
+ Rake::GemPackageTask.new(spec) do |pkg|
74
+ pkg.need_tar = true
75
+ end
76
+
77
+ desc "Release new version"
78
+ task :release => [:test, :sync_docs, :gem] do
79
+ require 'rubygems'
80
+ require 'rubyforge'
81
+ r = RubyForge.new
82
+ r.login
83
+ r.add_release spec.rubyforge_project,
84
+ spec.name,
85
+ spec.version,
86
+ File.join("pkg", "#{spec.name}-#{spec.version}.gem")
87
+ end
88
+
89
+ desc "Generate a gemspec file for GitHub"
90
+ task :gemspec do
91
+ File.open("#{spec.name}.gemspec", 'w') do |f|
92
+ f.write spec.to_ruby
93
+ end
94
+ end
@@ -0,0 +1,5 @@
1
+ Usage:
2
+
3
+ script/generate paperclip Class attachment1 (attachment2 ...)
4
+
5
+ This will create a migration that will add the proper columns to your class's table.
@@ -0,0 +1,27 @@
1
+ class PaperclipGenerator < Rails::Generator::NamedBase
2
+ attr_accessor :attachments, :migration_name
3
+
4
+ def initialize(args, options = {})
5
+ super
6
+ @class_name, @attachments = args[0], args[1..-1]
7
+ end
8
+
9
+ def manifest
10
+ file_name = generate_file_name
11
+ @migration_name = file_name.camelize
12
+ record do |m|
13
+ m.migration_template "paperclip_migration.rb.erb",
14
+ File.join('db', 'migrate'),
15
+ :migration_file_name => file_name
16
+ end
17
+ end
18
+
19
+ private
20
+
21
+ def generate_file_name
22
+ names = attachments.map{|a| a.underscore }
23
+ names = names[0..-2] + ["and", names[-1]] if names.length > 1
24
+ "add_attachments_#{names.join("_")}_to_#{@class_name.underscore}"
25
+ end
26
+
27
+ end
@@ -0,0 +1,19 @@
1
+ class <%= migration_name %> < ActiveRecord::Migration
2
+ def self.up
3
+ <% attachments.each do |attachment| -%>
4
+ add_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_file_name, :string
5
+ add_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_content_type, :string
6
+ add_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_file_size, :integer
7
+ add_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_updated_at, :datetime
8
+ <% end -%>
9
+ end
10
+
11
+ def self.down
12
+ <% attachments.each do |attachment| -%>
13
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_file_name
14
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_content_type
15
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_file_size
16
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_updated_at
17
+ <% end -%>
18
+ end
19
+ end
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.join(File.dirname(__FILE__), "lib", "paperclip")
@@ -0,0 +1,267 @@
1
+ # Paperclip allows file attachments that are stored in the filesystem. All graphical
2
+ # transformations are done using the Graphics/ImageMagick command line utilities and
3
+ # are stored in Tempfiles until the record is saved. Paperclip does not require a
4
+ # separate model for storing the attachment's information, instead adding a few simple
5
+ # columns to your table.
6
+ #
7
+ # Author:: Jon Yurek
8
+ # Copyright:: Copyright (c) 2008 thoughtbot, inc.
9
+ # License:: MIT License (http://www.opensource.org/licenses/mit-license.php)
10
+ #
11
+ # Paperclip defines an attachment as any file, though it makes special considerations
12
+ # for image files. You can declare that a model has an attached file with the
13
+ # +has_attached_file+ method:
14
+ #
15
+ # class User < ActiveRecord::Base
16
+ # has_attached_file :avatar, :styles => { :thumb => "100x100" }
17
+ # end
18
+ #
19
+ # user = User.new
20
+ # user.avatar = params[:user][:avatar]
21
+ # user.avatar.url
22
+ # # => "/users/avatars/4/original_me.jpg"
23
+ # user.avatar.url(:thumb)
24
+ # # => "/users/avatars/4/thumb_me.jpg"
25
+ #
26
+ # See the +has_attached_file+ documentation for more details.
27
+
28
+ require 'tempfile'
29
+ require 'paperclip/upfile'
30
+ require 'paperclip/iostream'
31
+ require 'paperclip/geometry'
32
+ require 'paperclip/thumbnail'
33
+ require 'paperclip/storage'
34
+ require 'paperclip/attachment'
35
+
36
+ # The base module that gets included in ActiveRecord::Base. See the
37
+ # documentation for Paperclip::ClassMethods for more useful information.
38
+ module Paperclip
39
+
40
+ VERSION = "2.1.5"
41
+
42
+ class << self
43
+ # Provides configurability to Paperclip. There are a number of options available, such as:
44
+ # * whiny_thumbnails: Will raise an error if Paperclip cannot process thumbnails of
45
+ # an uploaded image. Defaults to true.
46
+ # * image_magick_path: Defines the path at which to find the +convert+ and +identify+
47
+ # programs if they are not visible to Rails the system's search path. Defaults to
48
+ # nil, which uses the first executable found in the search path.
49
+ def options
50
+ @options ||= {
51
+ :whiny_thumbnails => true,
52
+ :image_magick_path => nil
53
+ }
54
+ end
55
+
56
+ def path_for_command command #:nodoc:
57
+ path = [options[:image_magick_path], command].compact
58
+ File.join(*path)
59
+ end
60
+
61
+ def run cmd, params = "", expected_outcodes = 0
62
+ output = `#{%Q[#{path_for_command(cmd)} #{params} 2>#{bit_bucket}].gsub(/\s+/, " ")}`
63
+ unless [expected_outcodes].flatten.include?($?.exitstatus)
64
+ raise PaperclipCommandLineError, "Error while running #{cmd}"
65
+ end
66
+ output
67
+ end
68
+
69
+ def bit_bucket
70
+ File.exists?("/dev/null") ? "/dev/null" : "NUL"
71
+ end
72
+
73
+ def included base #:nodoc:
74
+ base.extend ClassMethods
75
+ end
76
+ end
77
+
78
+ class PaperclipError < StandardError #:nodoc:
79
+ end
80
+
81
+ class PaperclipCommandLineError < StandardError #:nodoc:
82
+ end
83
+
84
+ class NotIdentifiedByImageMagickError < PaperclipError #:nodoc:
85
+ end
86
+
87
+ module ClassMethods
88
+ # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
89
+ # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
90
+ # The attribute returns a Paperclip::Attachment object which handles the management of
91
+ # that file. The intent is to make the attachment as much like a normal attribute. The
92
+ # thumbnails will be created when the new file is assigned, but they will *not* be saved
93
+ # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
94
+ # called on it, the attachment will *not* be deleted until +save+ is called. See the
95
+ # Paperclip::Attachment documentation for more specifics. There are a number of options
96
+ # you can set to change the behavior of a Paperclip attachment:
97
+ # * +url+: The full URL of where the attachment is publically accessible. This can just
98
+ # as easily point to a directory served directly through Apache as it can to an action
99
+ # that can control permissions. You can specify the full domain and path, but usually
100
+ # just an absolute path is sufficient. The leading slash must be included manually for
101
+ # absolute paths. The default value is
102
+ # "/:class/:attachment/:id/:style_:basename.:extension". See
103
+ # Paperclip::Attachment#interpolate for more information on variable interpolaton.
104
+ # :url => "/:attachment/:id/:style_:basename:extension"
105
+ # :url => "http://some.other.host/stuff/:class/:id_:extension"
106
+ # * +default_url+: The URL that will be returned if there is no attachment assigned.
107
+ # This field is interpolated just as the url is. The default value is
108
+ # "/:class/:attachment/missing_:style.png"
109
+ # has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
110
+ # User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
111
+ # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
112
+ # geometry strings at the ImageMagick website
113
+ # (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
114
+ # also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
115
+ # inside the dimensions and then crop the rest off (weighted at the center). The
116
+ # default value is to generate no thumbnails.
117
+ # * +default_style+: The thumbnail style that will be used by default URLs.
118
+ # Defaults to +original+.
119
+ # has_attached_file :avatar, :styles => { :normal => "100x100#" },
120
+ # :default_style => :normal
121
+ # user.avatar.url # => "/avatars/23/normal_me.png"
122
+ # * +whiny_thumbnails+: Will raise an error if Paperclip cannot process thumbnails of an
123
+ # uploaded image. This will ovrride the global setting for this attachment.
124
+ # Defaults to true.
125
+ # * +convert_options+: When creating thumbnails, use this free-form options
126
+ # field to pass in various convert command options. Typical options are "-strip" to
127
+ # remove all Exif data from the image (save space for thumbnails and avatars) or
128
+ # "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
129
+ # convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
130
+ # Note that this option takes a hash of options, each of which correspond to the style
131
+ # of thumbnail being generated. You can also specify :all as a key, which will apply
132
+ # to all of the thumbnails being generated. If you specify options for the :original,
133
+ # it would be best if you did not specify destructive options, as the intent of keeping
134
+ # the original around is to regenerate all the thumbnails when requirements change.
135
+ # has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
136
+ # :convert_options => {
137
+ # :all => "-strip",
138
+ # :negative => "-negate"
139
+ # }
140
+ # * +storage+: Chooses the storage backend where the files will be stored. The current
141
+ # choices are :filesystem and :s3. The default is :filesystem. Make sure you read the
142
+ # documentation for Paperclip::Storage::Filesystem and Paperclip::Storage::S3
143
+ # for backend-specific options.
144
+ def has_attached_file name, options = {}
145
+ include InstanceMethods
146
+
147
+ write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
148
+ attachment_definitions[name] = {:validations => {}}.merge(options)
149
+
150
+ after_save :save_attached_files
151
+ before_destroy :destroy_attached_files
152
+
153
+ define_method name do |*args|
154
+ a = attachment_for(name)
155
+ (args.length > 0) ? a.to_s(args.first) : a
156
+ end
157
+
158
+ define_method "#{name}=" do |file|
159
+ attachment_for(name).assign(file)
160
+ end
161
+
162
+ define_method "#{name}?" do
163
+ attachment_for(name).file?
164
+ end
165
+
166
+ validates_each(name) do |record, attr, value|
167
+ value.send(:flush_errors) unless value.valid?
168
+ end
169
+ end
170
+
171
+ # Places ActiveRecord-style validations on the size of the file assigned. The
172
+ # possible options are:
173
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
174
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
175
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
176
+ # * +message+: error message to display, use :min and :max as replacements
177
+ def validates_attachment_size name, options = {}
178
+ min = options[:greater_than] || (options[:in] && options[:in].first) || 0
179
+ max = options[:less_than] || (options[:in] && options[:in].last) || (1.0/0)
180
+ range = (min..max)
181
+ message = options[:message] || "file size must be between :min and :max bytes."
182
+
183
+ attachment_definitions[name][:validations][:size] = lambda do |attachment, instance|
184
+ if attachment.file? && !range.include?(attachment.size.to_i)
185
+ message.gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)
186
+ end
187
+ end
188
+ end
189
+
190
+ # Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.
191
+ def validates_attachment_thumbnails name, options = {}
192
+ attachment_definitions[name][:whiny_thumbnails] = true
193
+ end
194
+
195
+ # Places ActiveRecord-style validations on the presence of a file.
196
+ def validates_attachment_presence name, options = {}
197
+ message = options[:message] || "must be set."
198
+ attachment_definitions[name][:validations][:presence] = lambda do |attachment, instance|
199
+ message unless attachment.file?
200
+ end
201
+ end
202
+
203
+ # Places ActiveRecord-style validations on the content type of the file assigned. The
204
+ # possible options are:
205
+ # * +content_type+: Allowed content types. Can be a single content type or an array.
206
+ # Each type can be a String or a Regexp. It should be noted that Internet Explorer uploads
207
+ # files with content_types that you may not expect. For example, JPEG images are given
208
+ # image/pjpeg and PNGs are image/x-png, so keep that in mind when determining how you match.
209
+ # Allows all by default.
210
+ # * +message+: The message to display when the uploaded file has an invalid content type.
211
+ def validates_attachment_content_type name, options = {}
212
+ attachment_definitions[name][:validations][:content_type] = lambda do |attachment, instance|
213
+ valid_types = [options[:content_type]].flatten
214
+
215
+ unless attachment.original_filename.blank?
216
+ unless options[:content_type].blank?
217
+ content_type = attachment.instance_read(:content_type)
218
+ unless valid_types.any?{|t| t === content_type }
219
+ options[:message] || "is not one of the allowed file types."
220
+ end
221
+ end
222
+ end
223
+ end
224
+ end
225
+
226
+ # Returns the attachment definitions defined by each call to has_attached_file.
227
+ def attachment_definitions
228
+ read_inheritable_attribute(:attachment_definitions)
229
+ end
230
+
231
+ end
232
+
233
+ module InstanceMethods #:nodoc:
234
+ def attachment_for name
235
+ @attachments ||= {}
236
+ @attachments[name] ||= Attachment.new(name, self, self.class.attachment_definitions[name])
237
+ end
238
+
239
+ def each_attachment
240
+ self.class.attachment_definitions.each do |name, definition|
241
+ yield(name, attachment_for(name))
242
+ end
243
+ end
244
+
245
+ def save_attached_files
246
+ logger.info("[paperclip] Saving attachments.")
247
+ each_attachment do |name, attachment|
248
+ attachment.send(:save)
249
+ end
250
+ end
251
+
252
+ def destroy_attached_files
253
+ logger.info("[paperclip] Deleting attachments.")
254
+ each_attachment do |name, attachment|
255
+ attachment.send(:queue_existing_for_delete)
256
+ attachment.send(:flush_deletes)
257
+ end
258
+ end
259
+ end
260
+
261
+ end
262
+
263
+ # Set it all up.
264
+ if Object.const_defined?("ActiveRecord")
265
+ ActiveRecord::Base.send(:include, Paperclip)
266
+ File.send(:include, Paperclip::Upfile)
267
+ end