godfat-thumbo 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
data/CHANGES ADDED
@@ -0,0 +1,7 @@
1
+ = thumbs changes history
2
+
3
+ == thumbs 0.5 / 2008-10-22
4
+
5
+ * 1 major enhancement
6
+ * Birthday!
7
+ * extracted from Ludy::HasManyThumbnails!
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ = notice for other stuffs
2
+
3
+ * this project skeleton is built through Mr Bones 2.1.0:
4
+ gem install bones
5
+ http://codeforpeople.rubyforge.org/bones/
6
+
7
+ * test cases were written in mini-test.
data/README ADDED
@@ -0,0 +1,40 @@
1
+ = thumbo 0.5
2
+ by Lin Jen-Shin (a.k.a. godfat-真常[http://godfat.org])
3
+ godfat (XD) godfat.org
4
+
5
+ == LINKS:
6
+
7
+ * github-project[http://github.com/godfat/thumbo]
8
+ * rubyforge-project[http://rubyforge.org/projects/ludy]
9
+
10
+ == DESCRIPTION:
11
+
12
+ == FEATURES:
13
+
14
+ == SYNOPSIS:
15
+
16
+ == REQUIREMENTS:
17
+
18
+ * RMagick 2
19
+
20
+ == INSTALL:
21
+
22
+ * sudo gem install thumbo
23
+
24
+ == LICENSE:
25
+
26
+ Apache License 2.0
27
+
28
+ Copyright (c) 2008, Lin Jen-Shin (a.k.a. godfat 真常)
29
+
30
+ Licensed under the Apache License, Version 2.0 (the "License");
31
+ you may not use this file except in compliance with the License.
32
+ You may obtain a copy of the License at
33
+
34
+ http://www.apache.org/licenses/LICENSE-2.0
35
+
36
+ Unless required by applicable law or agreed to in writing, software
37
+ distributed under the License is distributed on an "AS IS" BASIS,
38
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
39
+ See the License for the specific language governing permissions and
40
+ limitations under the License.
@@ -0,0 +1,58 @@
1
+ # encoding: utf-8
2
+
3
+ begin
4
+ require 'bones'
5
+ Bones.setup
6
+ rescue LoadError
7
+ load 'tasks/setup.rb' # this line should already be there
8
+ end
9
+
10
+ PROJ.name = 'thumbo'
11
+ # supress warnings, there's too many warnings in dm-core
12
+ # PROJ.ruby_opts.delete '-w'
13
+
14
+ PROJ.gem.dependencies << ['rmagick', '>=2.6.0']
15
+ PROJ.gem.development_dependencies << ['minitest', '>=1.3.0']
16
+ # PROJ.gem.executables = ["bin/#{PROJ.name}"]
17
+
18
+ task :default do
19
+ Rake.application.options.show_task_pattern = /./
20
+ Rake.application.display_tasks_and_comments
21
+ end
22
+
23
+ namespace :gem do
24
+ desc "create #{PROJ.name}.gemspec"
25
+ task 'gemspec' do
26
+ puts "rake gem:debug > #{PROJ.name}.gemspec"
27
+ File.open("#{PROJ.name}.gemspec", 'w'){|spec| spec << `rake gem:debug`.sub(/.*/, '')}
28
+ end
29
+ end
30
+
31
+ PROJ.authors = 'Lin Jen-Shin (a.k.a. godfat 真常)'
32
+ PROJ.email = 'godfat (XD) godfat.org'
33
+ PROJ.url = "http://github.com/godfat/#{PROJ.name}"
34
+ PROJ.description = PROJ.summary = paragraphs_of('README', 'description').join("\n\n")
35
+ PROJ.changes = paragraphs_of('CHANGES', 0..1).join("\n\n")
36
+ PROJ.rubyforge.name = 'ludy'
37
+ PROJ.version = File.read("lib/#{PROJ.name}/version.rb").gsub(/.*VERSION = '(.*)'.*/m, '\1')
38
+
39
+ PROJ.manifest_file = 'Manifest'
40
+ PROJ.exclude += ['^Manifest$', '^tmp', 'tmp$', '^pkg',
41
+ '^\.gitignore$', '^ann-', '\.sqlite3$', '\.db$']
42
+
43
+ PROJ.rdoc.remote_dir = PROJ.name
44
+
45
+ PROJ.readme_file = 'README'
46
+ PROJ.rdoc.main = 'README'
47
+ PROJ.rdoc.exclude += ['Rakefile', '^tasks', '^test']
48
+ PROJ.rdoc.include << '\w+'
49
+ PROJ.rdoc.opts << '--diagram' if !WIN32 and `which dot` =~ %r/\/dot/
50
+ PROJ.rdoc.opts += ['--charset=utf-8', '--inline-source',
51
+ '--line-numbers', '--promiscuous']
52
+
53
+ PROJ.spec.opts << '--color'
54
+
55
+ PROJ.ann.file = "ann-#{PROJ.name}-#{PROJ.version}"
56
+ PROJ.ann.paragraphs.concat %w[LINKS SYNOPSIS REQUIREMENTS INSTALL LICENSE]
57
+
58
+ CLEAN.include Dir['**/*.rbc']
data/TODO ADDED
@@ -0,0 +1,2 @@
1
+
2
+ * mogilefs storage test case
@@ -0,0 +1,93 @@
1
+
2
+ require 'thumbo/proxy'
3
+ require 'thumbo/exceptions/file_not_found'
4
+
5
+ module Thumbo
6
+ def self.included model
7
+ model.extend(Thumbo::ClassMethod)
8
+ end
9
+
10
+ def self.calculate_dimension limit, width, height
11
+ long, short = width >= height ? [width, height] : [height, width]
12
+
13
+ if long <= limit # stay on
14
+ [width, height]
15
+
16
+ elsif width == height # square
17
+ [limit, limit]
18
+
19
+ else # detect which is longer
20
+
21
+ # assume width is longer
22
+ new_width, new_height = limit, short * (limit.to_f / long)
23
+
24
+ # swap if height is longer
25
+ new_width, new_height = new_height, new_width if long == height
26
+
27
+ [new_width, new_height]
28
+ end
29
+ end
30
+
31
+ module ClassMethod
32
+ def thumbo_storage
33
+ @thumbo_storage ||= begin
34
+ require 'thumbo/storages/filesystem'
35
+ Thumbo::Filesystem.new
36
+ end
37
+ end
38
+
39
+ def thumbo_common
40
+ {}
41
+ end
42
+
43
+ def thumbo_square
44
+ {}
45
+ end
46
+
47
+ def thumbo_labels
48
+ {}
49
+ end
50
+ end
51
+
52
+ def thumbos
53
+ @thumbos ||= init_thumbos
54
+ end
55
+
56
+ # same as thumbnail.filename, for writing
57
+ def thumbo_filename thumbo
58
+ "#{object_id}_#{thumbo.title}.#{thumbo.fileext}"
59
+ end
60
+
61
+ def thumbo_mime_type
62
+ thumbos[:original].mime_type
63
+ end
64
+
65
+ def create_thumbos after_scale = lambda{}
66
+ # scale thumbnails
67
+ self.class.thumbo_common.merge(self.class.thumbo_square).each_key{ |title|
68
+ after_scale[ thumbos[title].create ]
69
+ }
70
+
71
+ # the last one don't scale at all, but call hook too
72
+ after_scale[ thumbos[:original] ]
73
+
74
+ self
75
+ end
76
+
77
+ private
78
+ def init_thumbos
79
+ # just to make sure original is setup.
80
+ {:original => true}.merge(
81
+ self.class.thumbo_common.merge(
82
+ self.class.thumbo_square.merge(
83
+ self.class.thumbo_labels
84
+ )
85
+ )
86
+ ).inject({}){ |result, title_value|
87
+ title = title_value.first
88
+ result[title] = Thumbo::Proxy.new(self, title)
89
+ result
90
+ }
91
+ end
92
+
93
+ end # of Thumbs
@@ -0,0 +1,8 @@
1
+
2
+ module Thumbo
3
+ class FileNotFound < StandardError
4
+ def initialize filename
5
+ super("Thumbo: File `#{filename}' was not found.")
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,181 @@
1
+
2
+ require 'RMagick'
3
+
4
+ module Thumbo
5
+ class Proxy
6
+ attr_reader :title
7
+ def initialize owner, title
8
+ @owner, @title = owner, title
9
+ @image = nil # please stop warning me @image is not defined
10
+ end
11
+
12
+ # image processing
13
+ def image
14
+ @image || (self.image = read_image)
15
+ end
16
+
17
+ def image_with_timeout time_limit = 5
18
+ @image || (self.image = read_image_with_timeout(time_limit))
19
+ end
20
+
21
+ def image= new_image
22
+ release
23
+ @image = new_image
24
+ end
25
+
26
+ # is this helpful or not?
27
+ def release
28
+ @image = nil
29
+ GC.start
30
+ self
31
+ end
32
+
33
+ # e.g.,
34
+ # thumbnails[:original].from_blob uploaded_file.read
35
+ def from_blob blob, &block
36
+ self.image = Magick::ImageList.new.from_blob(blob, &block)
37
+ self
38
+ end
39
+
40
+ def to_blob
41
+ self.image.to_blob
42
+ end
43
+
44
+ # convert format to website displable image format
45
+ def convert_format_for_website
46
+ image.format = 'PNG' unless ['GIF', 'JPEG'].include?(image.format)
47
+ end
48
+
49
+ # create thumbnails in the image list (Magick::ImageList)
50
+ def create
51
+ return if title == :original
52
+ release
53
+ limit = owner.class.thumbo_common[title]
54
+
55
+ if limit
56
+ create_common(limit)
57
+
58
+ else
59
+ limit = owner.class.thumbo_square[title]
60
+ create_square(limit)
61
+
62
+ end
63
+
64
+ self
65
+ end
66
+
67
+ def write
68
+ storage.write(self.filename, to_blob)
69
+ end
70
+
71
+ # delegate all
72
+ def method_missing msg, *args, &block
73
+ raise 'fetch image first if you want to operate the image' unless @image
74
+
75
+ if image.__respond_to__?(msg) # operate ImageList, a dirty way because of RMagick...
76
+ [image.__send__(msg, *args, &block)]
77
+
78
+ elsif image.first.respond_to?(msg) # operate each Image in ImageList
79
+ image.to_a.map{ |layer| layer.__send__(msg, *args, &block) }
80
+
81
+ else # no such method...
82
+ super(msg, *args, &block)
83
+
84
+ end
85
+ end
86
+
87
+ # storage related
88
+ def storage
89
+ owner.class.thumbo_storage
90
+ end
91
+
92
+ def paths
93
+ storage.paths(filename)
94
+ end
95
+
96
+ def delete
97
+ storage.delete(filename)
98
+ end
99
+
100
+ # owner delegate
101
+ def filename
102
+ owner.thumbo_filename self
103
+ end
104
+
105
+ def uri
106
+ owner.thumbo_uri self
107
+ end
108
+
109
+ # attribute
110
+ def dimension img = image.first
111
+ [img.columns, img.rows]
112
+ end
113
+
114
+ def mime_type
115
+ image.first.mime_type
116
+ end
117
+
118
+ def fileext
119
+ if @image
120
+ case ext = image.first.format
121
+ when 'PNG8'; 'png'
122
+ when 'PNG24'; 'png'
123
+ when 'PNG32'; 'png'
124
+ when 'GIF87'; 'gif'
125
+ when 'JPEG'; 'jpg'
126
+ when 'PJPEG'; 'jpg'
127
+ when 'BMP2'; 'bmp'
128
+ when 'BMP3'; 'bmp'
129
+ when 'TIFF64'; 'tiff'
130
+ else; ext.downcase
131
+ end
132
+
133
+ elsif owner.respond_to?(:thumbo_default_fileext)
134
+ owner.thumbo_default_fileext
135
+
136
+ else
137
+ raise "please implement #{owner.class}\#thumbo_default_fileext or Thumbo can't guess the file extension"
138
+
139
+ end
140
+ end
141
+
142
+ protected
143
+ attr_reader :owner
144
+
145
+ def create_common limit
146
+ # can't use map since it have different meaning to collect here
147
+ self.image = owner.thumbos[:original].image.collect{ |layer|
148
+ # i hate column and row!! nerver remember which is width...
149
+ new_dimension = Thumbo.calculate_dimension(limit, layer.columns, layer.rows)
150
+
151
+ # no need to scale
152
+ if new_dimension == dimension(layer)
153
+ layer
154
+
155
+ # scale to new_dimension
156
+ else
157
+ layer.scale(*new_dimension)
158
+
159
+ end
160
+ }
161
+ end
162
+
163
+ def create_square limit
164
+ self.image = owner.thumbos[:original].image.collect{ |layer|
165
+ layer.crop_resized(limit, limit).enhance
166
+ }
167
+ end
168
+
169
+ private
170
+ # fetch image from storage to memory
171
+ # raises Magick::ImageMagickError
172
+ def read_image
173
+ Magick::ImageList.new.from_blob(storage.read(filename))
174
+ end
175
+
176
+ def read_image_with_timeout time_limit = 5
177
+ require 'timeout'
178
+ timeout(time_limit){ fetch }
179
+ end
180
+ end
181
+ end
@@ -0,0 +1,27 @@
1
+
2
+ class AbstractStorage
3
+ def read filename
4
+ raise NotImplementedError
5
+ end
6
+
7
+ def write filename, blob
8
+ raise NotImplementedError
9
+ end
10
+
11
+ def delete filename
12
+ raise NotImplementedError
13
+ end
14
+
15
+ def paths filename
16
+ raise NotImplementedError
17
+ end
18
+
19
+ def exist? filename
20
+ raise NotImplementedError
21
+ end
22
+
23
+ protected
24
+ def raise_file_not_found filename
25
+ raise Thumbo::FileNotFound.new(filename)
26
+ end
27
+ end
@@ -0,0 +1,61 @@
1
+
2
+ require 'thumbo/storages/abstract'
3
+ require 'fileutils'
4
+ require 'digest/md5'
5
+
6
+ module Thumbo
7
+ class Filesystem < AbstractStorage
8
+ attr_accessor :path, :prefix_size
9
+ def initialize opts = {}
10
+ @path = opts[:path] || 'public/images'
11
+ @prefix_size = opts[:prefix_size] || 1
12
+ end
13
+
14
+ def read filename
15
+ File.read(calculate_path(filename))
16
+
17
+ rescue Errno::ENOENT
18
+ raise_file_not_found(filename)
19
+
20
+ end
21
+
22
+ def write filename, blob
23
+ target = calculate_path(filename)
24
+ FileUtils.mkdir_p(target.split('/')[0..-2].join('/'))
25
+ (File.open(target, 'w') << blob).close
26
+ end
27
+
28
+ def delete filename
29
+ target = calculate_path(filename)
30
+ if File.exist?(target)
31
+ File.delete(target)
32
+
33
+ else
34
+ raise_file_not_found(filename)
35
+
36
+ end
37
+ end
38
+
39
+ def paths filename
40
+ if target = exist?(filename)
41
+ [target]
42
+
43
+ else
44
+ raise_file_not_found(filename)
45
+
46
+ end
47
+ end
48
+
49
+ def exist? filename
50
+ target = calculate_path(filename)
51
+ File.exist?(target) ? target : false
52
+ end
53
+
54
+ private
55
+ def calculate_path filename
56
+ File.join( path,
57
+ Digest::MD5.hexdigest(filename)[0, prefix_size],
58
+ filename )
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,56 @@
1
+
2
+ require 'thumbo/storages/abstract'
3
+ begin
4
+ require 'mogilefs'
5
+ rescue LoadError
6
+ raise LoadError.new("Please install gem mogilefs-client")
7
+ end
8
+
9
+ module Thumbo
10
+ class Mogilefs < AbstractStorage
11
+ attr_accessor :klass, :domain, :hosts, :timeout_time
12
+ attr_accessor :client
13
+ def initialize opts = {}
14
+ @klass = opts[:klass] || 'thumbo'
15
+ @domain = opts[:domain] || 'thumbo'
16
+ @hosts = opts[:hosts] || ['127.0.0.1:6001']
17
+ @timeout_time = opts[:timeout_time] || 2
18
+ end
19
+
20
+ def read filename
21
+ client.get_file_data(filename)
22
+
23
+ rescue MogileFS::Backend::UnknownKeyError
24
+ raise_file_not_found(filename)
25
+
26
+ end
27
+
28
+ def write filename, blob
29
+ client.store_content(filename, klass, blob)
30
+ end
31
+
32
+ def delete filename
33
+ client.delete(filename)
34
+
35
+ rescue MogileFS::Backend::UnknownKeyError
36
+ raise_file_not_found(filename)
37
+
38
+ end
39
+
40
+ # raises MogileFS::Backend::UnknownKeyError
41
+ def paths filename
42
+ client.get_paths(filename)
43
+
44
+ rescue MogileFS::Backend::UnknownKeyError
45
+ raise_file_not_found(filename)
46
+
47
+ end
48
+
49
+ def client
50
+ @client ||=
51
+ MogileFS::MogileFS.new( :domain => domain,
52
+ :hosts => hosts,
53
+ :timeout => timeout_time )
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,4 @@
1
+
2
+ module Thumbo
3
+ VERSION = '0.5.0'
4
+ end
@@ -0,0 +1,6 @@
1
+
2
+ require 'rubygems'
3
+ require 'minitest/unit'
4
+ MiniTest::Unit.autorun
5
+
6
+ require 'thumbo'
Binary file
@@ -0,0 +1,48 @@
1
+
2
+ require 'test/helper'
3
+
4
+ class Photo
5
+ include Thumbo
6
+ def self.thumbo_storage
7
+ @thumbo_storage ||= Thumbo::Filesystem.new(:path => 'tmp', :prefix_size => 2)
8
+ end
9
+
10
+ def self.thumbo_common
11
+ {:common => 200}
12
+ end
13
+
14
+ def self.thumbo_square
15
+ {:square => 50}
16
+ end
17
+
18
+ def thumbo_filename thumbo
19
+ "#{self.object_id}_#{thumbo.title}.#{thumbo.fileext}"
20
+ end
21
+
22
+ def thumbo_uri thumbo
23
+ first, last = thumbo.filename.split('_')
24
+ "http://img.godfat.org/photos/#{first}_zzz_#{last}"
25
+ end
26
+
27
+ def thumbo_default_fileext
28
+ 'png'
29
+ end
30
+
31
+ end
32
+
33
+ class StorageTest < MiniTest::Unit::TestCase
34
+ def test_uri
35
+ p = Photo.new
36
+ t = p.thumbos[:original]
37
+ t.from_blob(File.open('test/ruby.png').read)
38
+
39
+ assert_equal( "http://img.godfat.org/photos/#{p.object_id}_zzz_original.png",
40
+ p.thumbos[:original].uri )
41
+ end
42
+
43
+ def test_raises
44
+ assert_raises(Thumbo::FileNotFound) do
45
+ Photo.new.thumbos[:original].delete
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,103 @@
1
+
2
+ require 'test/helper'
3
+
4
+ class RubyLogo
5
+ include Thumbo
6
+
7
+ self.thumbo_storage.path = './tmp'
8
+
9
+ def self.thumbo_common
10
+ { :small => 240, :thumb => 110 }
11
+ end
12
+
13
+ def self.thumbo_square
14
+ { :square_medium => 48, :square_small => 24 }
15
+ end
16
+
17
+ def self.thumbo_labels
18
+ { :original => 'o', :raw => 'z',
19
+ :small => 's', :thumb => 't',
20
+ :square_medium => 'msq', :square_small => 'ssq' }
21
+ end
22
+
23
+ attr_accessor :mime_type, :log
24
+ def initialize blob = nil
25
+ if blob
26
+ thumbos[:raw].from_blob(blob).write
27
+ thumbos[:original].image = thumbos[:raw].image
28
+ thumbos[:raw].release
29
+ self.mime_type = thumbos[:original].mime_type
30
+ end
31
+ self.log = []
32
+ end
33
+
34
+ def create
35
+ create_thumbos(lambda{ |thumbo|
36
+ log << thumbo.dimension
37
+ thumbo.write
38
+ thumbo.release
39
+ })
40
+ end
41
+
42
+ # same as thumbnail.filename
43
+ def thumbo_filename thumbo
44
+ "#{self.class}_#{checksum}_" +
45
+ "#{self.class.thumbo_labels[thumbo.title]}.#{thumbo.fileext}"
46
+ end
47
+
48
+ def thumbo_default_fileext
49
+ case ext = mime_type.sub(%r{^image/}, '').downcase
50
+ when 'jpeg'; 'jpg'
51
+ else; ext
52
+ end
53
+ end
54
+
55
+ def checksum; 'abcdefg'; end
56
+ end
57
+
58
+ class TestThumbo < MiniTest::Unit::TestCase
59
+ Dims00 = [[ 24, 24], [ 48, 48],
60
+ [109,110], [239,240], [995,996]]
61
+ Dims90 = Dims00.map(&:reverse)
62
+
63
+ def test_first
64
+ logo = RubyLogo.new File.open('test/ruby.png').read
65
+ assert_kind_of String, logo.thumbos[:original].to_blob
66
+
67
+ logo.create
68
+ assert_dimension Dims00, logo.log.sort
69
+ assert_dimension Dims00, read_dimension
70
+
71
+ logo2 = RubyLogo.new
72
+ logo2.mime_type = logo.mime_type
73
+
74
+ logo2.thumbos[:original].image
75
+ logo2.thumbos[:original].rotate! 90
76
+ logo2.create
77
+
78
+ assert_dimension Dims90[0..-2], logo2.log.sort
79
+ assert_dimension Dims90[0..-2] << Dims00[-1], read_dimension
80
+
81
+ ensure
82
+ cleanup
83
+ end
84
+
85
+ def assert_dimension should, real
86
+ should.zip(real).each{ |s, r|
87
+ assert_equal s, r
88
+ }
89
+ end
90
+
91
+ def read_dimension
92
+ Magick::ImageList.new.read(*Dir['tmp/**/*.png']).to_a.map{ |img|
93
+ [img.columns, img.rows]
94
+ }.sort
95
+ end
96
+
97
+ def cleanup
98
+ Dir['tmp/*'].each{ |prefix|
99
+ File.delete(*Dir["#{prefix}/*.png"])
100
+ Dir.rmdir(prefix)
101
+ }
102
+ end
103
+ end
@@ -0,0 +1,42 @@
1
+
2
+ # -*- encoding: utf-8 -*-
3
+
4
+ Gem::Specification.new do |s|
5
+ s.name = %q{thumbo}
6
+ s.version = "0.5.0"
7
+
8
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
9
+ s.authors = ["Lin Jen-Shin (a.k.a. godfat \347\234\237\345\270\270)"]
10
+ s.date = %q{2008-11-21}
11
+ s.description = %q{}
12
+ s.email = %q{godfat (XD) godfat.org}
13
+ s.extra_rdoc_files = ["CHANGES", "LICENSE", "NOTICE", "README", "TODO", "thumbo.gemspec"]
14
+ s.files = ["CHANGES", "LICENSE", "NOTICE", "README", "Rakefile", "TODO", "lib/thumbo.rb", "lib/thumbo/exceptions/file_not_found.rb", "lib/thumbo/proxy.rb", "lib/thumbo/storages/abstract.rb", "lib/thumbo/storages/filesystem.rb", "lib/thumbo/storages/mogilefs.rb", "lib/thumbo/version.rb", "tasks/ann.rake", "tasks/bones.rake", "tasks/gem.rake", "tasks/git.rake", "tasks/manifest.rake", "tasks/notes.rake", "tasks/post_load.rake", "tasks/rdoc.rake", "tasks/rubyforge.rake", "tasks/setup.rb", "tasks/spec.rake", "tasks/svn.rake", "tasks/test.rake", "test/helper.rb", "test/ruby.png", "test/test_storage.rb", "test/test_thumbo.rb", "thumbo.gemspec"]
15
+ s.has_rdoc = true
16
+ s.homepage = %q{http://github.com/godfat/thumbo}
17
+ s.rdoc_options = ["--diagram", "--charset=utf-8", "--inline-source", "--line-numbers", "--promiscuous", "--main", "README"]
18
+ s.require_paths = ["lib"]
19
+ s.rubyforge_project = %q{ludy}
20
+ s.rubygems_version = %q{1.3.1}
21
+ s.summary = %q{}
22
+ s.test_files = ["test/test_storage.rb", "test/test_thumbo.rb"]
23
+
24
+ if s.respond_to? :specification_version then
25
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
26
+ s.specification_version = 2
27
+
28
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
29
+ s.add_runtime_dependency(%q<rmagick>, [">= 2.6.0"])
30
+ s.add_development_dependency(%q<bones>, [">= 2.1.0"])
31
+ s.add_development_dependency(%q<minitest>, [">= 1.3.0"])
32
+ else
33
+ s.add_dependency(%q<rmagick>, [">= 2.6.0"])
34
+ s.add_dependency(%q<bones>, [">= 2.1.0"])
35
+ s.add_dependency(%q<minitest>, [">= 1.3.0"])
36
+ end
37
+ else
38
+ s.add_dependency(%q<rmagick>, [">= 2.6.0"])
39
+ s.add_dependency(%q<bones>, [">= 2.1.0"])
40
+ s.add_dependency(%q<minitest>, [">= 1.3.0"])
41
+ end
42
+ end
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: godfat-thumbo
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.5.0
5
+ platform: ruby
6
+ authors:
7
+ - "Lin Jen-Shin (a.k.a. godfat \xE7\x9C\x9F\xE5\xB8\xB8)"
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2008-11-21 00:00:00 -08:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: rmagick
17
+ version_requirement:
18
+ version_requirements: !ruby/object:Gem::Requirement
19
+ requirements:
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 2.6.0
23
+ version:
24
+ - !ruby/object:Gem::Dependency
25
+ name: bones
26
+ version_requirement:
27
+ version_requirements: !ruby/object:Gem::Requirement
28
+ requirements:
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 2.1.0
32
+ version:
33
+ - !ruby/object:Gem::Dependency
34
+ name: minitest
35
+ version_requirement:
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: 1.3.0
41
+ version:
42
+ description: ""
43
+ email: godfat (XD) godfat.org
44
+ executables: []
45
+
46
+ extensions: []
47
+
48
+ extra_rdoc_files:
49
+ - CHANGES
50
+ - LICENSE
51
+ - NOTICE
52
+ - README
53
+ - TODO
54
+ - thumbo.gemspec
55
+ files:
56
+ - CHANGES
57
+ - LICENSE
58
+ - NOTICE
59
+ - README
60
+ - Rakefile
61
+ - TODO
62
+ - lib/thumbo.rb
63
+ - lib/thumbo/exceptions/file_not_found.rb
64
+ - lib/thumbo/proxy.rb
65
+ - lib/thumbo/storages/abstract.rb
66
+ - lib/thumbo/storages/filesystem.rb
67
+ - lib/thumbo/storages/mogilefs.rb
68
+ - lib/thumbo/version.rb
69
+ - tasks/ann.rake
70
+ - tasks/bones.rake
71
+ - tasks/gem.rake
72
+ - tasks/git.rake
73
+ - tasks/manifest.rake
74
+ - tasks/notes.rake
75
+ - tasks/post_load.rake
76
+ - tasks/rdoc.rake
77
+ - tasks/rubyforge.rake
78
+ - tasks/setup.rb
79
+ - tasks/spec.rake
80
+ - tasks/svn.rake
81
+ - tasks/test.rake
82
+ - test/helper.rb
83
+ - test/ruby.png
84
+ - test/test_storage.rb
85
+ - test/test_thumbo.rb
86
+ - thumbo.gemspec
87
+ has_rdoc: true
88
+ homepage: http://github.com/godfat/thumbo
89
+ post_install_message:
90
+ rdoc_options:
91
+ - --diagram
92
+ - --charset=utf-8
93
+ - --inline-source
94
+ - --line-numbers
95
+ - --promiscuous
96
+ - --main
97
+ - README
98
+ require_paths:
99
+ - lib
100
+ required_ruby_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: "0"
105
+ version:
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: "0"
111
+ version:
112
+ requirements: []
113
+
114
+ rubyforge_project: ludy
115
+ rubygems_version: 1.2.0
116
+ signing_key:
117
+ specification_version: 2
118
+ summary: ""
119
+ test_files:
120
+ - test/test_storage.rb
121
+ - test/test_thumbo.rb