jcnetdev-paperclip 1.0.20080704

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
+
data/README ADDED
@@ -0,0 +1,48 @@
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
+ end
23
+
24
+ def self.down
25
+ remove_column :users, :avatar_file_name
26
+ remove_column :users, :avatar_content_type
27
+ remove_column :users, :avatar_file_size
28
+ end
29
+ end
30
+
31
+ In your edit and new views:
32
+
33
+ <% form_for :user, @user, :url => user_path, :html => { :multipart => true } do |form| %>
34
+ <%= form.file_field :avatar %>
35
+ <% end %>
36
+
37
+ In your controller:
38
+
39
+ def create
40
+ @user = User.create( params[:user] )
41
+ end
42
+
43
+ In your show view:
44
+
45
+ <%= image_tag @user.avatar.url %>
46
+ <%= image_tag @user.avatar.url(:medium) %>
47
+ <%= image_tag @user.avatar.url(:thumb) %>
48
+
data/README.rdoc ADDED
@@ -0,0 +1,48 @@
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
+ end
23
+
24
+ def self.down
25
+ remove_column :users, :avatar_file_name
26
+ remove_column :users, :avatar_content_type
27
+ remove_column :users, :avatar_file_size
28
+ end
29
+ end
30
+
31
+ In your edit and new views:
32
+
33
+ <% form_for :user, @user, :url => user_path, :html => { :multipart => true } do |form| %>
34
+ <%= form.file_field :avatar %>
35
+ <% end %>
36
+
37
+ In your controller:
38
+
39
+ def create
40
+ @user = User.create( params[:user] )
41
+ end
42
+
43
+ In your show view:
44
+
45
+ <%= image_tag @user.avatar.url %>
46
+ <%= image_tag @user.avatar.url(:medium) %>
47
+ <%= image_tag @user.avatar.url(:thumb) %>
48
+
data/Rakefile ADDED
@@ -0,0 +1,84 @@
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/"
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}/**/*"].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 = ["README"]
66
+ s.rdoc_options << '--line-numbers' << '--inline-source'
67
+ s.requirements << "ImageMagick"
68
+ end
69
+
70
+ Rake::GemPackageTask.new(spec) do |pkg|
71
+ pkg.need_tar = true
72
+ end
73
+
74
+ desc "Release new version"
75
+ task :release => [:test, :sync_docs, :gem] do
76
+ require 'rubygems'
77
+ require 'rubyforge'
78
+ r = RubyForge.new
79
+ r.login
80
+ r.add_release spec.rubyforge_project,
81
+ spec.name,
82
+ spec.version,
83
+ File.join("pkg", "#{spec.name}-#{spec.version}.gem")
84
+ end
@@ -0,0 +1,5 @@
1
+ Usage:
2
+
3
+ script/generate attachment 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",
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,17 @@
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
+ <% end -%>
8
+ end
9
+
10
+ def self.down
11
+ <% attachments.each do |attachment| -%>
12
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_file_name
13
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_content_type
14
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :<%= attachment %>_file_size
15
+ <% end -%>
16
+ end
17
+ end
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.dirname(__FILE__) + "/rails/init"
data/lib/paperclip.rb ADDED
@@ -0,0 +1,239 @@
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.2"
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 included base #:nodoc:
62
+ base.extend ClassMethods
63
+ end
64
+ end
65
+
66
+ class PaperclipError < StandardError #:nodoc:
67
+ end
68
+
69
+ class NotIdentifiedByImageMagickError < PaperclipError #:nodoc:
70
+ end
71
+
72
+ module ClassMethods
73
+ # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
74
+ # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
75
+ # The attribute returns a Paperclip::Attachment object which handles the management of
76
+ # that file. The intent is to make the attachment as much like a normal attribute. The
77
+ # thumbnails will be created when the new file is assigned, but they will *not* be saved
78
+ # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
79
+ # called on it, the attachment will *not* be deleted until +save+ is called. See the
80
+ # Paperclip::Attachment documentation for more specifics. There are a number of options
81
+ # you can set to change the behavior of a Paperclip attachment:
82
+ # * +url+: The full URL of where the attachment is publically accessible. This can just
83
+ # as easily point to a directory served directly through Apache as it can to an action
84
+ # that can control permissions. You can specify the full domain and path, but usually
85
+ # just an absolute path is sufficient. The leading slash must be included manually for
86
+ # absolute paths. The default value is "/:class/:attachment/:id/:style_:filename". See
87
+ # Paperclip::Attachment#interpolate for more information on variable interpolaton.
88
+ # :url => "/:attachment/:id/:style_:basename:extension"
89
+ # :url => "http://some.other.host/stuff/:class/:id_:extension"
90
+ # * +default_url+: The URL that will be returned if there is no attachment assigned.
91
+ # This field is interpolated just as the url is. The default value is
92
+ # "/:class/:attachment/missing_:style.png"
93
+ # has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
94
+ # User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
95
+ # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
96
+ # geometry strings at the ImageMagick website
97
+ # (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
98
+ # also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
99
+ # inside the dimensions and then crop the rest off (weighted at the center). The
100
+ # default value is to generate no thumbnails.
101
+ # * +default_style+: The thumbnail style that will be used by default URLs.
102
+ # Defaults to +original+.
103
+ # has_attached_file :avatar, :styles => { :normal => "100x100#" },
104
+ # :default_style => :normal
105
+ # user.avatar.url # => "/avatars/23/normal_me.png"
106
+ # * +whiny_thumbnails+: Will raise an error if Paperclip cannot process thumbnails of an
107
+ # uploaded image. This will ovrride the global setting for this attachment.
108
+ # Defaults to true.
109
+ # * +storage+: Chooses the storage backend where the files will be stored. The current
110
+ # choices are :filesystem and :s3. The default is :filesystem. Make sure you read the
111
+ # documentation for Paperclip::Storage::Filesystem and Paperclip::Storage::S3
112
+ # for backend-specific options.
113
+ def has_attached_file name, options = {}
114
+ include InstanceMethods
115
+
116
+ write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
117
+ attachment_definitions[name] = {:validations => []}.merge(options)
118
+
119
+ after_save :save_attached_files
120
+ before_destroy :destroy_attached_files
121
+
122
+ define_method name do |*args|
123
+ a = attachment_for(name)
124
+ (args.length > 0) ? a.to_s(args.first) : a
125
+ end
126
+
127
+ define_method "#{name}=" do |file|
128
+ attachment_for(name).assign(file)
129
+ end
130
+
131
+ define_method "#{name}?" do
132
+ ! attachment_for(name).original_filename.blank?
133
+ end
134
+
135
+ validates_each(name) do |record, attr, value|
136
+ value.send(:flush_errors)
137
+ end
138
+ end
139
+
140
+ # Places ActiveRecord-style validations on the size of the file assigned. The
141
+ # possible options are:
142
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
143
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
144
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
145
+ # * +message+: error message to display, use :min and :max as replacements
146
+ def validates_attachment_size name, options = {}
147
+ attachment_definitions[name][:validations] << lambda do |attachment, instance|
148
+ unless options[:greater_than].nil?
149
+ options[:in] = (options[:greater_than]..(1/0)) # 1/0 => Infinity
150
+ end
151
+ unless options[:less_than].nil?
152
+ options[:in] = (0..options[:less_than])
153
+ end
154
+ unless attachment.original_filename.blank? || options[:in].include?(instance[:"#{name}_file_size"].to_i)
155
+ min = options[:in].first
156
+ max = options[:in].last
157
+
158
+ if options[:message]
159
+ options[:message].gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)
160
+ else
161
+ "file size is not between #{min} and #{max} bytes."
162
+ end
163
+ end
164
+ end
165
+ end
166
+
167
+ # Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.
168
+ def validates_attachment_thumbnails name, options = {}
169
+ attachment_definitions[name][:whiny_thumbnails] = true
170
+ end
171
+
172
+ # Places ActiveRecord-style validations on the presence of a file.
173
+ def validates_attachment_presence name, options = {}
174
+ attachment_definitions[name][:validations] << lambda do |attachment, instance|
175
+ if attachment.original_filename.blank?
176
+ options[:message] || "must be set."
177
+ end
178
+ end
179
+ end
180
+
181
+ # Places ActiveRecord-style validations on the content type of the file assigned. The
182
+ # possible options are:
183
+ # * +content_type+: Allowed content types. Can be a single content type or an array. Allows all by default.
184
+ # * +message+: The message to display when the uploaded file has an invalid content type.
185
+ def validates_attachment_content_type name, options = {}
186
+ attachment_definitions[name][:validations] << lambda do |attachment, instance|
187
+ valid_types = [options[:content_type]].flatten
188
+
189
+ unless attachment.original_filename.nil?
190
+ unless options[:content_type].blank?
191
+ content_type = instance[:"#{name}_content_type"]
192
+ unless valid_types.any?{|t| t === content_type }
193
+ options[:message] || ActiveRecord::Errors.default_error_messages[:inclusion]
194
+ end
195
+ end
196
+ end
197
+ end
198
+ end
199
+
200
+ # Returns the attachment definitions defined by each call to has_attached_file.
201
+ def attachment_definitions
202
+ read_inheritable_attribute(:attachment_definitions)
203
+ end
204
+
205
+ end
206
+
207
+ module InstanceMethods #:nodoc:
208
+ def attachment_for name
209
+ @attachments ||= {}
210
+ @attachments[name] ||= Attachment.new(name, self, self.class.attachment_definitions[name])
211
+ end
212
+
213
+ def each_attachment
214
+ self.class.attachment_definitions.each do |name, definition|
215
+ yield(name, attachment_for(name))
216
+ end
217
+ end
218
+
219
+ def save_attached_files
220
+ each_attachment do |name, attachment|
221
+ attachment.send(:save)
222
+ end
223
+ end
224
+
225
+ def destroy_attached_files
226
+ each_attachment do |name, attachment|
227
+ attachment.send(:queue_existing_for_delete)
228
+ attachment.send(:flush_deletes)
229
+ end
230
+ end
231
+ end
232
+
233
+ end
234
+
235
+ # Set it all up.
236
+ if Object.const_defined?("ActiveRecord")
237
+ ActiveRecord::Base.send(:include, Paperclip)
238
+ File.send(:include, Paperclip::Upfile)
239
+ end