miloops-attachment_fu 3.2.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. data/CHANGELOG +63 -0
  2. data/LICENSE +20 -0
  3. data/README +253 -0
  4. data/Rakefile +22 -0
  5. data/amazon_s3.yml.tpl +17 -0
  6. data/install.rb +7 -0
  7. data/lib/geometry.rb +96 -0
  8. data/lib/pothoven-attachment_fu.rb +23 -0
  9. data/lib/technoweenie/attachment_fu.rb +578 -0
  10. data/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb +211 -0
  11. data/lib/technoweenie/attachment_fu/backends/db_file_backend.rb +39 -0
  12. data/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +126 -0
  13. data/lib/technoweenie/attachment_fu/backends/s3_backend.rb +394 -0
  14. data/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +66 -0
  15. data/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +59 -0
  16. data/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +80 -0
  17. data/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +142 -0
  18. data/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +66 -0
  19. data/rackspace_cloudfiles.yml.tpl +14 -0
  20. data/test/backends/db_file_test.rb +16 -0
  21. data/test/backends/file_system_test.rb +143 -0
  22. data/test/backends/remote/cloudfiles_test.rb +102 -0
  23. data/test/backends/remote/s3_test.rb +119 -0
  24. data/test/base_attachment_tests.rb +77 -0
  25. data/test/basic_test.rb +120 -0
  26. data/test/database.yml +18 -0
  27. data/test/extra_attachment_test.rb +67 -0
  28. data/test/fixtures/attachment.rb +304 -0
  29. data/test/fixtures/files/fake/rails.png +0 -0
  30. data/test/fixtures/files/foo.txt +1 -0
  31. data/test/fixtures/files/rails.jpg +0 -0
  32. data/test/fixtures/files/rails.png +0 -0
  33. data/test/geometry_test.rb +114 -0
  34. data/test/processors/core_image_test.rb +58 -0
  35. data/test/processors/gd2_test.rb +51 -0
  36. data/test/processors/image_science_test.rb +54 -0
  37. data/test/processors/mini_magick_test.rb +122 -0
  38. data/test/processors/rmagick_test.rb +272 -0
  39. data/test/schema.rb +136 -0
  40. data/test/test_helper.rb +180 -0
  41. data/test/validation_test.rb +55 -0
  42. data/vendor/red_artisan/core_image/filters/color.rb +27 -0
  43. data/vendor/red_artisan/core_image/filters/effects.rb +31 -0
  44. data/vendor/red_artisan/core_image/filters/perspective.rb +25 -0
  45. data/vendor/red_artisan/core_image/filters/quality.rb +25 -0
  46. data/vendor/red_artisan/core_image/filters/scale.rb +47 -0
  47. data/vendor/red_artisan/core_image/filters/watermark.rb +32 -0
  48. data/vendor/red_artisan/core_image/processor.rb +123 -0
  49. metadata +98 -0
data/CHANGELOG ADDED
@@ -0,0 +1,63 @@
1
+ * Nov 15, 2012 *
2
+ * Removed 'crop:' option as already included when prefixing geometry with a 'c'. Add note to docs.
3
+ * Added option to sharpen resized images ':sharpen_on_resize'
4
+
5
+ * Oct 26, 2012 *
6
+ * Merged with https://github.com/tdd/attachment_fu fork to include GEM support for use in Rails 3.2, and bumped version to 3.2.x to indicate Rails 3.2 support.
7
+
8
+ * Oct 25, 2012 *
9
+ * Fix to support Ruby 1.9.3
10
+ * Image cropping support (append 'crop:' to desired file size when resizing)
11
+
12
+ * Mar 15, 2010 *
13
+ * Added a symbol syntax for parent-type-based size spec: calls the corresponding method on the current asset instance to
14
+ get a Hash of required thumbnails. Lets us dynamically specify what would otherwise be hard-coded, which is useful
15
+ when the set of thumbnails for a given parent type varies depending on the usage context.
16
+
17
+ * Aug 6, 2009 *
18
+ * JPEG quality control finalized across processors (although CoreImage applies it in a rather fuzzy-logic way), with tests.
19
+
20
+ * Aug 4, 2009 *
21
+ * Supports the :aspect/'!' geometry flag in all processors
22
+ (thanks to http://www.deepcalm.com/writing/cropped-thumbnails-in-attachment_fu-using-imagescience)
23
+ * JPEG quality control on thumbnailing/resizing (still buggy on Rmagick/MiniMagick though).
24
+ * Moves from GIF to PNG regardless of the source file extension's case (used to require lowercase)
25
+ * Auto-orients image (if EXIF suggests it) prior to processing with RMagickProcessor
26
+ * Fixes non-image upload tests (both regular files and Merb files)
27
+ * Fixes obsolete failures on RMagick tests (aspect_ratio tested but not initialized anymore due to new callback architecture
28
+
29
+ * Apr 17 2008 *
30
+ * amazon_s3.yml is now passed through ERB before being passed to AWS::S3 [François Beausoleil]
31
+
32
+ * Mar 22 2008 *
33
+ * Some tweaks to support Rails 2.0 and Rails 2.1 due to ActiveSupport::Callback changes.
34
+ Thanks to http://blog.methodmissing.com/2008/1/19/edge-callback-refactorings-attachment_fu/
35
+
36
+ * Feb. 26, 2008 *
37
+ * remove breakpoint from test_helper, makes test suite crazy (at least Rails 2+) [Rob Sanheim]
38
+ * make S3 test really optional [Rob Sanheim]
39
+
40
+ * Nov 27, 2007 *
41
+ * Handle properly ImageScience thumbnails resized from a gif file [Matt Aimonetti]
42
+ * Save thumbnails file size properly when using ImageScience [Matt Aimonetti]
43
+ * fixed s3 config file loading with latest versions of Rails [Matt Aimonetti]
44
+
45
+ * April 2, 2007 *
46
+
47
+ * don't copy the #full_filename to the default #temp_paths array if it doesn't exist
48
+ * add default ID partitioning for attachments
49
+ * add #binmode call to Tempfile (note: ruby should be doing this!) [Eric Beland]
50
+ * Check for current type of :thumbnails option.
51
+ * allow customization of the S3 configuration file path with the :s3_config_path option.
52
+ * Don't try to remove thumbnails if there aren't any. Closes #3 [ben stiglitz]
53
+
54
+ * BC * (before changelog)
55
+
56
+ * add default #temp_paths entry [mattly]
57
+ * add MiniMagick support to attachment_fu [Isacc]
58
+ * update #destroy_file to clear out any empty directories too [carlivar]
59
+ * fix references to S3Backend module [Hunter Hillegas]
60
+ * make #current_data public with db_file and s3 backends [ebryn]
61
+ * oops, actually svn add the files for s3 backend. [Jeffrey Hardy]
62
+ * experimental s3 support, egad, no tests.... [Jeffrey Hardy]
63
+ * doh, fix a few bad references to ActsAsAttachment [sixty4bit]
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 rick olson
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,253 @@
1
+ attachment-fu
2
+ =============
3
+
4
+ attachment_fu is a plugin by Rick Olson (aka technoweenie <http://techno-weenie.net>) and is the successor to acts_as_attachment. To get a basic run-through of its capabilities, check out Mike Clark's tutorial <http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu>.
5
+
6
+
7
+ attachment_fu functionality
8
+ ===========================
9
+
10
+ attachment_fu facilitates file uploads in Ruby on Rails. There are a few storage options for the actual file data, but the plugin always at a minimum stores metadata for each file in the database.
11
+
12
+ There are four storage options for files uploaded through attachment_fu:
13
+ File system
14
+ Database file
15
+ Amazon S3
16
+ Rackspace (Mosso) Cloud Files
17
+
18
+ Each method of storage many options associated with it that will be covered in the following section. Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml, the Rackspace Cloud Files storage requires you to modify config/rackspace_cloudfiles.yml, and the Database file storage requires an extra table.
19
+
20
+
21
+ attachment_fu models
22
+ ====================
23
+
24
+ For all three of these storage options a table of metadata is required. This table will contain information about the file (hence the 'meta') and its location. This table has no restrictions on naming, unlike the extra table required for database storage, which must have a table name of db_files (and by convention a model of DbFile).
25
+
26
+ In the model there are two methods made available by this plugins: has_attachment and validates_as_attachment.
27
+
28
+ has_attachment(options = {})
29
+ This method accepts the options in a hash:
30
+ :content_type # Allowed content types.
31
+ # Allows all by default. Use :image to allow all standard image types.
32
+ #
33
+ :min_size # Minimum size allowed.
34
+ # 1 byte is the default.
35
+ #
36
+ :max_size # Maximum size allowed.
37
+ # 1.megabyte is the default.
38
+ #
39
+ :size # Range of sizes allowed.
40
+ # (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
41
+ #
42
+ :resize_to # Used by RMagick to resize images.
43
+ # Pass either an array of width/height, or a geometry string.
44
+ #
45
+ :thumbnails # Specifies a set of thumbnails to generate.
46
+ # This accepts a hash of filename suffixes and RMagick resizing options.
47
+ # This option need only be included if you want thumbnailing.
48
+ # If you have a polymorphic parent relationship, you can provide parent-type-specific
49
+ # thumbnail settings by using a pair with the type string as key and a Hash of thumbnail
50
+ # definitions, or a method symbol, as value. The method symbol will call the named
51
+ # method in order to get a dynamically-built Hash of thumbnail definitions, which gives
52
+ # you full flexibility.
53
+ # AttachmentFu automatically detects your first polymorphic +belongs_to+ relationship.
54
+ #
55
+ :thumbnail_class # Set which model class to use for thumbnails.
56
+ # This current attachment class is used by default.
57
+ #
58
+ :jpeg_quality # Used to provide explicit JPEG quality for thumbnail/resize saves. Can have multiple
59
+ # formats:
60
+ # * Integer from 0 (basically crap) to 100 (basically lossless, fat files).
61
+ # * When relying on tdd-image_science, you can also use one of its +JPEG_xxx+ constants
62
+ # for predefined ratios/settings.
63
+ # * You can also use a Hash, with keys being either thumbnail symbols (I repeat:
64
+ # _symbols_) or surface boundaries. A surface boundary is a string starting with either
65
+ # '<' or '>=', followed by a number of pixels. This lets you specify per-thumbnail or
66
+ # per-general-thumbnail-"size" JPEG qualities. (which can be useful when you have a
67
+ # _lot_ of thumbnail options). Surface example: +{ '<2000' => 90, '>=2000' => 75 }+.
68
+ #
69
+ # Defaults vary depending on the processor (ImageScience: 100%,
70
+ # Rmagick/MiniMagick/Gd2: 75%, CoreImage: auto-adjust).
71
+ # Note that only tdd-image_science (available from GitHub) currently supports explicit
72
+ # JPEG quality; the default image_science currently forces 100%.
73
+ #
74
+ :path_prefix # Path to store the uploaded files in.
75
+ # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the
76
+ # S3 and Cloud Files backend.
77
+ # Setting this sets the :storage to :file_system.
78
+ #
79
+ :partition # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true.
80
+ # Only applicable to the :file_system backend.
81
+ #
82
+ :storage # Specifies the storage system to use..
83
+ # Defaults to :db_file. Options are :file_system, :db_file, :s3, and :cloud_files.
84
+ #
85
+ :cloudfront # If using S3 for storage, this option allows for serving the files via Amazon CloudFront.
86
+ # Defaults to false.
87
+ #
88
+ :processor # Sets the image processor to use for resizing of the attached image.
89
+ # Options include ImageScience, Rmagick, MiniMagick, Gd2 and CoreImage. Default is
90
+ # whatever is installed.
91
+ #
92
+ :uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to
93
+ # true.
94
+ #
95
+ :association_options # attachment_fu automatically defines associations with thumbnails with has_many and
96
+ # belongs_to. If there are any additional options that you want to pass to these methods,
97
+ # then specify them here.
98
+
99
+
100
+ Examples:
101
+ has_attachment :max_size => 1.kilobyte
102
+ has_attachment :size => 1.megabyte..2.megabytes
103
+ has_attachment :content_type => 'application/pdf'
104
+ has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
105
+ has_attachment :content_type => :image, :resize_to => [50,50]
106
+ has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
107
+ has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
108
+ has_attachment :storage => :file_system, :path_prefix => 'public/files'
109
+ has_attachment :storage => :file_system, :path_prefix => 'public/files',
110
+ :content_type => :image, :resize_to => [50,50], :partition => false
111
+ has_attachment :storage => :file_system, :path_prefix => 'public/files',
112
+ :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
113
+ has_attachment :storage => :s3
114
+ has_attachment :store => :s3, :cloudfront => true
115
+ has_attachment :storage => :cloud_files
116
+
117
+ # Let's say we have a polymorphic belongs_to, e.g. called 'imageable', where imageable_type (or whatever the
118
+ # :foreign_type option was set to) can be, among other things, 'Product', 'User' or 'Editorial', each of which
119
+ # should have extra thumbnails:
120
+
121
+ has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50',
122
+ :products => { :large_thumb => '169x169!', :zoomed => '500x500>' },
123
+ :editorials => { :fullsize => '150x100>' },
124
+ :users => { :avatar => '64x64!' } }
125
+
126
+ # JPEG qualities…
127
+
128
+ has_attachment :jpeg_quality => 75
129
+ has_attachment :jpeg_quality => 80 | ImageScience::JPEG_PROGRESSIVE
130
+ has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' },
131
+ :jpeg_quality => { nil => 75, :thumb => 90, :geometry => 90 }
132
+ has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' },
133
+ :jpeg_quality => { '<2000' => 90, '>=2000' => 75 }
134
+ }
135
+
136
+ validates_as_attachment
137
+ This method prevents files outside of the valid range (:min_size to :max_size, or the :size range) from being saved. It does not however, halt the upload of such files. They will be uploaded into memory regardless of size before validation.
138
+
139
+ Example:
140
+ validates_as_attachment
141
+
142
+
143
+ attachment_fu migrations
144
+ ========================
145
+
146
+ Fields for attachment_fu metadata tables...
147
+ in general:
148
+ size, :integer # file size in bytes
149
+ content_type, :string # mime type, ex: application/mp3
150
+ filename, :string # sanitized filename
151
+ that reference images:
152
+ height, :integer # in pixels
153
+ width, :integer # in pixels
154
+ that reference images that will be thumbnailed:
155
+ parent_id, :integer # id of parent image (on the same table, a self-referencing foreign-key).
156
+ # Only populated if the current object is a thumbnail.
157
+ thumbnail, :string # the 'type' of thumbnail this attachment record describes.
158
+ # Only populated if the current object is a thumbnail.
159
+ # Usage:
160
+ # [ In Model 'Avatar' ]
161
+ # has_attachment :content_type => :image,
162
+ # :storage => :file_system,
163
+ # :max_size => 500.kilobytes,
164
+ # :resize_to => '320x200>',
165
+ # :thumbnails => { :small => '10x10>',
166
+ # :thumb => '100x100>' }
167
+ # [ Elsewhere ]
168
+ # @user.avatar.thumbnails.first.thumbnail #=> 'small'
169
+ that reference files stored in the database (:db_file):
170
+ db_file_id, :integer # id of the file in the database (foreign key)
171
+
172
+ Field for attachment_fu db_files table:
173
+ data, :binary # binary file data, for use in database file storage
174
+
175
+
176
+ attachment_fu views
177
+ ===================
178
+
179
+ There are two main views tasks that will be directly affected by attachment_fu: upload forms and displaying uploaded images.
180
+
181
+ There are two parts of the upload form that differ from typical usage.
182
+ 1. Include ':multipart => true' in the html options of the form_for tag.
183
+ Example:
184
+ <% form_for(:attachment_metadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %>
185
+
186
+ 2. Use the file_field helper with :uploaded_data as the field name.
187
+ Example:
188
+ <%= form.file_field :uploaded_data %>
189
+
190
+ Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage.
191
+
192
+ public_filename(thumbnail = nil)
193
+ Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail.
194
+ Examples:
195
+ attachment_obj.public_filename #=> /attachments/2/file.jpg
196
+ attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg
197
+ attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg
198
+
199
+ When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document.
200
+
201
+
202
+ attachment_fu controllers
203
+ =========================
204
+
205
+ There are two considerations to take into account when using attachment_fu in controllers.
206
+
207
+ The first is when the files have no publicly accessible path and need to be downloaded through an action.
208
+
209
+ Example:
210
+ def readme
211
+ send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline'
212
+ end
213
+
214
+ See the possible values for send_file for reference.
215
+
216
+
217
+ The second is when saving the file when submitted from a form.
218
+ Example in view:
219
+ <%= form.file_field :attachable, :uploaded_data %>
220
+
221
+ Example in controller:
222
+ def create
223
+ @attachable_file = AttachmentMetadataModel.new(params[:attachable])
224
+ if @attachable_file.save
225
+ flash[:notice] = 'Attachment was successfully created.'
226
+ redirect_to attachable_url(@attachable_file)
227
+ else
228
+ render :action => :new
229
+ end
230
+ end
231
+
232
+ attachement_fu scripting
233
+ ====================================
234
+
235
+ You may wish to import a large number of images or attachments.
236
+ The following example shows how to upload a file from a script.
237
+
238
+ #!/usr/bin/env ./script/runner
239
+
240
+ # required to use ActionController::TestUploadedFile
241
+ require 'action_controller'
242
+ require 'action_controller/test_process.rb'
243
+
244
+ path = "./public/images/x.jpg"
245
+
246
+ # mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system
247
+ # mimetype = `file -ib #{path}`.gsub(/\n/,"")
248
+
249
+ mimetype = "image/jpeg"
250
+
251
+ # This will "upload" the file at path and create the new model.
252
+ @attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))
253
+ @attachable.save
data/Rakefile ADDED
@@ -0,0 +1,22 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+
5
+ desc 'Default: run unit tests.'
6
+ task :default => :test
7
+
8
+ desc 'Test the attachment_fu plugin.'
9
+ Rake::TestTask.new(:test) do |t|
10
+ t.libs << 'lib'
11
+ t.pattern = 'test/**/*_test.rb'
12
+ t.verbose = true
13
+ end
14
+
15
+ desc 'Generate documentation for the attachment_fu plugin.'
16
+ Rake::RDocTask.new(:rdoc) do |rdoc|
17
+ rdoc.rdoc_dir = 'rdoc'
18
+ rdoc.title = 'ActsAsAttachment'
19
+ rdoc.options << '--line-numbers --inline-source'
20
+ rdoc.rdoc_files.include('README')
21
+ rdoc.rdoc_files.include('lib/**/*.rb')
22
+ end
data/amazon_s3.yml.tpl ADDED
@@ -0,0 +1,17 @@
1
+ development:
2
+ bucket_name: appname_development
3
+ access_key_id:
4
+ secret_access_key:
5
+ distribution_domain: XXXX.cloudfront.net
6
+
7
+ test:
8
+ bucket_name: appname_test
9
+ access_key_id:
10
+ secret_access_key:
11
+ distribution_domain: XXXX.cloudfront.net
12
+
13
+ production:
14
+ bucket_name: appname
15
+ access_key_id:
16
+ secret_access_key:
17
+ distribution_domain: XXXX.cloudfront.net
data/install.rb ADDED
@@ -0,0 +1,7 @@
1
+ require 'fileutils'
2
+
3
+ s3_config = File.dirname(__FILE__) + '/../../../config/amazon_s3.yml'
4
+ FileUtils.cp File.dirname(__FILE__) + '/amazon_s3.yml.tpl', s3_config unless File.exist?(s3_config)
5
+ cloudfiles_config = File.dirname(__FILE__) + '/../../../config/rackspace_cloudfiles.yml'
6
+ FileUtils.cp File.dirname(__FILE__) + '/rackspace_cloudfiles.yml.tpl', cloudfiles_config unless File.exist?(cloudfiles_config)
7
+ puts IO.read(File.join(File.dirname(__FILE__), 'README'))
data/lib/geometry.rb ADDED
@@ -0,0 +1,96 @@
1
+ # This Geometry class was yanked from RMagick. However, it lets ImageMagick handle the actual change_geometry.
2
+ # Use #new_dimensions_for to get new dimensions
3
+ # Used so I can use spiffy RMagick geometry strings with ImageScience
4
+ class Geometry
5
+ # @ is removed until support for them is added
6
+ FLAGS = ['', '%', '<', '>', '!']#, '@']
7
+ RFLAGS = { '%' => :percent,
8
+ '!' => :aspect,
9
+ '<' => :>,
10
+ '>' => :<,
11
+ '@' => :area }
12
+
13
+ attr_accessor :width, :height, :x, :y, :flag
14
+
15
+ def initialize(width=nil, height=nil, x=nil, y=nil, flag=nil)
16
+ # Support floating-point width and height arguments so Geometry
17
+ # objects can be used to specify Image#density= arguments.
18
+ raise ArgumentError, "width must be >= 0: #{width}" if width < 0
19
+ raise ArgumentError, "height must be >= 0: #{height}" if height < 0
20
+ @width = width.to_f
21
+ @height = height.to_f
22
+ @x = x.to_i
23
+ @y = y.to_i
24
+ @flag = flag
25
+ end
26
+
27
+ # Construct an object from a geometry string
28
+ RE = /\A(\d*)(?:x(\d+)?)?([-+]\d+)?([-+]\d+)?([%!<>@]?)\Z/
29
+
30
+ def self.from_s(str)
31
+ raise(ArgumentError, "no geometry string specified") unless str
32
+
33
+ if m = RE.match(str)
34
+ new(m[1].to_i, m[2].to_i, m[3].to_i, m[4].to_i, RFLAGS[m[5]])
35
+ else
36
+ raise ArgumentError, "invalid geometry format"
37
+ end
38
+ end
39
+
40
+ # Convert object to a geometry string
41
+ def to_s
42
+ str = ''
43
+ str << "%g" % @width if @width > 0
44
+ str << 'x' if (@width > 0 || @height > 0)
45
+ str << "%g" % @height if @height > 0
46
+ str << "%+d%+d" % [@x, @y] if (@x != 0 || @y != 0)
47
+ str << FLAGS[@flag.to_i]
48
+ end
49
+
50
+ # attempts to get new dimensions for the current geometry string given these old dimensions.
51
+ # This doesn't implement the aspect flag (!) or the area flag (@). PDI
52
+ def new_dimensions_for(orig_width, orig_height)
53
+ new_width = orig_width
54
+ new_height = orig_height
55
+
56
+ case @flag
57
+ when :percent
58
+ scale_x = @width.zero? ? 100 : @width
59
+ scale_y = @height.zero? ? @width : @height
60
+ new_width = scale_x.to_f * (orig_width.to_f / 100.0)
61
+ new_height = scale_y.to_f * (orig_height.to_f / 100.0)
62
+ when :aspect
63
+ new_width = @width unless @width.nil?
64
+ new_height = @height unless @height.nil?
65
+ when :<, :>, nil
66
+ scale_factor =
67
+ if new_width.zero? || new_height.zero?
68
+ 1.0
69
+ else
70
+ if @width.nonzero? && @height.nonzero?
71
+ [@width.to_f / new_width.to_f, @height.to_f / new_height.to_f].min
72
+ else
73
+ @width.nonzero? ? (@width.to_f / new_width.to_f) : (@height.to_f / new_height.to_f)
74
+ end
75
+ end
76
+ new_width = scale_factor * new_width.to_f
77
+ new_height = scale_factor * new_height.to_f
78
+ new_width = orig_width if @flag && orig_width.send(@flag, new_width)
79
+ new_height = orig_height if @flag && orig_height.send(@flag, new_height)
80
+ end
81
+
82
+ [new_width, new_height].collect! { |v| [v.round, 1].max }
83
+ end
84
+ end
85
+
86
+ class Array
87
+ # allows you to get new dimensions for the current array of dimensions with a given geometry string
88
+ #
89
+ # [50, 64] / '40>' # => [40, 51]
90
+ def /(geometry)
91
+ raise ArgumentError, "Only works with a [width, height] pair" if size != 2
92
+ raise ArgumentError, "Must pass a valid geometry string or object" unless geometry.is_a?(String) || geometry.is_a?(Geometry)
93
+ geometry = Geometry.from_s(geometry) if geometry.is_a?(String)
94
+ geometry.new_dimensions_for first, last
95
+ end
96
+ end