thumbo 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/CHANGES ADDED
@@ -0,0 +1,11 @@
1
+ = thumbs changes history
2
+
3
+ == thumbo 0.6 - 2010-05-31
4
+
5
+ * stable undocumented release
6
+
7
+ == thumbo 0.5 - 2008-10-22
8
+
9
+ * 1 major enhancement
10
+ * Birthday!
11
+ * 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.
@@ -0,0 +1,41 @@
1
+ = thumbo 0.6
2
+ by Lin Jen-Shin (aka godfat 真常)
3
+ godfat (XD) godfat.org
4
+
5
+ == LINKS:
6
+
7
+ * github[http://github.com/godfat/thumbo]
8
+
9
+ == DESCRIPTION:
10
+
11
+ create thumbnails via RMagick
12
+
13
+ == FEATURES:
14
+
15
+ == SYNOPSIS:
16
+
17
+ == REQUIREMENTS:
18
+
19
+ * RMagick 2
20
+
21
+ == INSTALL:
22
+
23
+ * gem install thumbo
24
+
25
+ == LICENSE:
26
+
27
+ Apache License 2.0
28
+
29
+ Copyright (c) 2008-2010, Lin Jen-Shin (aka godfat 真常)
30
+
31
+ Licensed under the Apache License, Version 2.0 (the "License");
32
+ you may not use this file except in compliance with the License.
33
+ You may obtain a copy of the License at
34
+
35
+ http://www.apache.org/licenses/LICENSE-2.0
36
+
37
+ Unless required by applicable law or agreed to in writing, software
38
+ distributed under the License is distributed on an "AS IS" BASIS,
39
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
40
+ See the License for the specific language governing permissions and
41
+ limitations under the License.
@@ -0,0 +1,35 @@
1
+ # encoding: utf-8
2
+
3
+ begin
4
+ require 'bones'
5
+ rescue LoadError
6
+ abort '### Please install the "bones" gem ###'
7
+ end
8
+
9
+ ensure_in_path 'lib'
10
+ proj = 'thumbo'
11
+ require "#{proj}/version"
12
+
13
+ Bones{
14
+ version Thumbo::VERSION
15
+
16
+ # ruby_opts [''] # silence warning, too many in addressable and/or dm-core
17
+ depend_on 'rmagick', :version => '>=2.6.0'
18
+
19
+ name proj
20
+ url "http://github.com/godfat/#{proj}"
21
+ authors 'Lin Jen-Shin (aka godfat 真常)'
22
+ email 'godfat (XD) godfat.org'
23
+
24
+ history_file 'CHANGES'
25
+ readme_file 'README.rdoc'
26
+ ignore_file '.gitignore'
27
+ rdoc.include ['\w+']
28
+ }
29
+
30
+ CLEAN.include Dir['**/*.rbc']
31
+
32
+ task :default do
33
+ Rake.application.options.show_task_pattern = /./
34
+ Rake.application.display_tasks_and_comments
35
+ end
data/TODO ADDED
@@ -0,0 +1,3 @@
1
+
2
+ * mogilefs storage test case
3
+ * easier way to create a thumbnail from a line of code
@@ -0,0 +1,99 @@
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
+ def thumbo_filename thumbo
57
+ "#{object_id}_#{thumbo.title}.#{thumbo.fileext}"
58
+ end
59
+
60
+ def thumbo_uri thumbo
61
+ paths = thumbo.paths
62
+ paths[rand(paths.size)]
63
+ end
64
+
65
+ def thumbo_mime_type
66
+ thumbos[:original].mime_type
67
+ end
68
+
69
+ def create_thumbos after_scale = lambda{}, &block
70
+ after_scale = block if block_given?
71
+
72
+ # scale thumbnails
73
+ self.class.thumbo_common.merge(self.class.thumbo_square).each_key{ |title|
74
+ after_scale[ thumbos[title].create ]
75
+ }
76
+
77
+ # the last one don't scale at all, but call hook too
78
+ after_scale[ thumbos[:original] ]
79
+
80
+ self
81
+ end
82
+
83
+ private
84
+ def init_thumbos
85
+ # just to make sure original is setup.
86
+ {:original => true}.merge(
87
+ self.class.thumbo_common.merge(
88
+ self.class.thumbo_square.merge(
89
+ self.class.thumbo_labels
90
+ )
91
+ )
92
+ ).inject({}){ |result, title_value|
93
+ title = title_value.first
94
+ result[title] = Thumbo::Proxy.new(self, title)
95
+ result
96
+ }
97
+ end
98
+
99
+ 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,185 @@
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
+ # check if image exists in memory
18
+ def image?
19
+ @image
20
+ end
21
+
22
+ def image_with_timeout time_limit = 5
23
+ @image || (self.image = read_image_with_timeout(time_limit))
24
+ end
25
+
26
+ def image= new_image
27
+ release
28
+ @image = new_image
29
+ end
30
+
31
+ # is this helpful or not?
32
+ def release
33
+ @image = nil
34
+ GC.start
35
+ self
36
+ end
37
+
38
+ # e.g.,
39
+ # thumbnails[:original].from_blob uploaded_file.read
40
+ def from_blob blob, &block
41
+ self.image = Magick::ImageList.new.from_blob(blob, &block)
42
+ self
43
+ end
44
+
45
+ def to_blob &block
46
+ self.image.to_blob(&block)
47
+ end
48
+
49
+ # convert format to website displable image format
50
+ def convert_format_for_website
51
+ image.format = 'PNG' unless ['GIF', 'JPEG'].include?(image.format)
52
+ end
53
+
54
+ # create thumbnails in the image list (Magick::ImageList)
55
+ def create
56
+ return if title == :original
57
+ release
58
+ limit = owner.class.thumbo_common[title]
59
+
60
+ if limit
61
+ create_common(limit)
62
+
63
+ else
64
+ limit = owner.class.thumbo_square[title]
65
+ create_square(limit)
66
+
67
+ end
68
+
69
+ self
70
+ end
71
+
72
+ def write filename = nil, &block
73
+ storage.write(filename || self.filename, to_blob(&block))
74
+ end
75
+
76
+ # delegate all
77
+ def method_missing msg, *args, &block
78
+ raise 'fetch image first if you want to operate the image' unless @image
79
+
80
+ if image.__respond_to__?(msg) # operate ImageList, a dirty way because of RMagick...
81
+ [image.__send__(msg, *args, &block)]
82
+
83
+ elsif image.first.respond_to?(msg) # operate each Image in ImageList
84
+ image.to_a.map{ |layer| layer.__send__(msg, *args, &block) }
85
+
86
+ else # no such method...
87
+ super(msg, *args, &block)
88
+
89
+ end
90
+ end
91
+
92
+ # storage related
93
+ def storage
94
+ owner.class.thumbo_storage
95
+ end
96
+
97
+ def paths
98
+ storage.paths(filename)
99
+ end
100
+
101
+ def delete
102
+ storage.delete(filename)
103
+ end
104
+
105
+ # owner delegate
106
+ def filename
107
+ owner.thumbo_filename self
108
+ end
109
+
110
+ def uri
111
+ owner.thumbo_uri self
112
+ end
113
+
114
+ # attribute
115
+ def dimension img = image.first
116
+ [img.columns, img.rows]
117
+ end
118
+
119
+ def mime_type
120
+ image.first.mime_type
121
+ end
122
+
123
+ def fileext
124
+ if @image
125
+ case ext = image.first.format
126
+ when 'PNG8'; 'png'
127
+ when 'PNG24'; 'png'
128
+ when 'PNG32'; 'png'
129
+ when 'GIF87'; 'gif'
130
+ when 'JPEG'; 'jpg'
131
+ when 'PJPEG'; 'jpg'
132
+ when 'BMP2'; 'bmp'
133
+ when 'BMP3'; 'bmp'
134
+ when 'TIFF64'; 'tiff'
135
+ else; ext.downcase
136
+ end
137
+
138
+ elsif owner.respond_to?(:thumbo_default_fileext)
139
+ owner.thumbo_default_fileext
140
+
141
+ else
142
+ raise "please implement #{owner.class}\#thumbo_default_fileext or Thumbo can't guess the file extension"
143
+
144
+ end
145
+ end
146
+
147
+ protected
148
+ attr_reader :owner
149
+
150
+ def create_common limit
151
+ # can't use map since it have different meaning to collect here
152
+ self.image = owner.thumbos[:original].image.collect{ |layer|
153
+ # i hate column and row!! nerver remember which is width...
154
+ new_dimension = Thumbo.calculate_dimension(limit, layer.columns, layer.rows)
155
+
156
+ # no need to scale
157
+ if new_dimension == dimension(layer)
158
+ layer
159
+
160
+ # scale to new_dimension
161
+ else
162
+ layer.scale(*new_dimension)
163
+
164
+ end
165
+ }
166
+ end
167
+
168
+ def create_square limit
169
+ self.image = owner.thumbos[:original].image.collect{ |layer|
170
+ layer.crop_resized(limit, limit).enhance
171
+ }
172
+ end
173
+
174
+ private
175
+ # fetch image from storage to memory
176
+ # raises Magick::ImageMagickError
177
+ def read_image
178
+ Magick::ImageList.new.from_blob(storage.read(filename))
179
+ end
180
+
181
+ def read_image_with_timeout time_limit = 5
182
+ Timeout.timeout(time_limit){ fetch }
183
+ end
184
+ end
185
+ end
@@ -0,0 +1,33 @@
1
+
2
+ module Thumbo
3
+ class AbstractStorage
4
+ def read filename
5
+ raise NotImplementedError
6
+ end
7
+
8
+ def write filename, blob
9
+ raise NotImplementedError
10
+ end
11
+
12
+ def write_file filename, file
13
+ raise NotImplementedError
14
+ end
15
+
16
+ def delete filename
17
+ raise NotImplementedError
18
+ end
19
+
20
+ def paths filename
21
+ raise NotImplementedError
22
+ end
23
+
24
+ def exist? filename
25
+ raise NotImplementedError
26
+ end
27
+
28
+ protected
29
+ def raise_file_not_found filename
30
+ raise Thumbo::FileNotFound.new(filename)
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,73 @@
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/thumbo'
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 = ensure_path(filename)
24
+ (File.open(target, 'w') << blob).close
25
+ end
26
+
27
+ def write_file filename, file
28
+ target = ensure_path(filename)
29
+ FileUtils.cp(file.path, target)
30
+ end
31
+
32
+ def delete filename
33
+ target = calculate_path(filename)
34
+ if File.exist?(target)
35
+ File.delete(target)
36
+
37
+ else
38
+ raise_file_not_found(filename)
39
+
40
+ end
41
+ end
42
+
43
+ def paths filename
44
+ if target = exist?(filename)
45
+ [target]
46
+
47
+ else
48
+ raise_file_not_found(filename)
49
+
50
+ end
51
+ end
52
+
53
+ def exist? filename
54
+ target = calculate_path(filename)
55
+ File.exist?(target) ? target : false
56
+ end
57
+
58
+ def prefix filename
59
+ Digest::MD5.hexdigest(filename)[0, prefix_size]
60
+ end
61
+
62
+ private
63
+ def calculate_path filename
64
+ File.join( path, prefix(filename), filename )
65
+ end
66
+
67
+ def ensure_path filename
68
+ target = calculate_path(filename)
69
+ FileUtils.mkdir_p(target.split('/')[0..-2].join('/'))
70
+ target
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,72 @@
1
+
2
+ require 'thumbo/storages/abstract'
3
+
4
+ begin
5
+ require 'mogilefs'
6
+ rescue LoadError
7
+ raise LoadError.new("Please install gem mogilefs-client")
8
+ end
9
+
10
+ module Thumbo
11
+ class Mogilefs < AbstractStorage
12
+ attr_accessor :klass, :domain, :hosts, :timeout_time
13
+ attr_accessor :client
14
+ def initialize opts = {}
15
+ @klass = opts[:klass] || 'thumbo'
16
+ @domain = opts[:domain] || 'thumbo'
17
+ @hosts = opts[:hosts] || ['127.0.0.1:6001']
18
+ @timeout_time = opts[:timeout_time] || 2
19
+ end
20
+
21
+ def read filename
22
+ Timeout.timeout(timeout_time){
23
+ paths(filename).each{ |path|
24
+ begin
25
+ return client.get_file_data(filename)
26
+ rescue SystemCallError
27
+ next
28
+ end
29
+ }
30
+ }
31
+ end
32
+
33
+ def write filename, blob
34
+ client.store_content(filename, klass, blob)
35
+ end
36
+
37
+ def write_file filename, file
38
+ client.store_file(filename, klass, file)
39
+ end
40
+
41
+ def delete filename
42
+ client.delete(filename)
43
+
44
+ rescue MogileFS::Backend::UnknownKeyError
45
+ raise_file_not_found(filename)
46
+
47
+ end
48
+
49
+ def paths filename
50
+ client.get_paths(filename)
51
+
52
+ rescue MogileFS::Backend::UnknownKeyError
53
+ raise_file_not_found(filename)
54
+
55
+ end
56
+
57
+ def exist? filename
58
+ target = paths(filename)
59
+ target[ rand(target.size) ]
60
+
61
+ rescue Thumbo::FileNotFound
62
+ false
63
+ end
64
+
65
+ def client
66
+ @client ||=
67
+ MogileFS::MogileFS.new( :domain => domain,
68
+ :hosts => hosts,
69
+ :timeout => timeout_time )
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,4 @@
1
+
2
+ module Thumbo
3
+ VERSION = '0.6.0'
4
+ end
@@ -0,0 +1,13 @@
1
+
2
+ require 'rubygems'
3
+
4
+ TestCase = begin
5
+ require 'minitest/unit'
6
+ MiniTest::Unit.autorun
7
+ MiniTest::Unit::TestCase
8
+ rescue LoadError
9
+ require 'test/unit'
10
+ Test::Unit::TestCase
11
+ end
12
+
13
+ require 'thumbo'
Binary file
@@ -0,0 +1,86 @@
1
+
2
+ require 'test/helper'
3
+ require 'digest/md5'
4
+
5
+ class Photo
6
+ include Thumbo
7
+ def self.thumbo_storage
8
+ @thumbo_storage ||= Thumbo::Filesystem.new(:path => 'tmp', :prefix_size => 2)
9
+ end
10
+
11
+ def self.thumbo_common
12
+ {:common => 200}
13
+ end
14
+
15
+ def self.thumbo_square
16
+ {:square => 50}
17
+ end
18
+
19
+ def thumbo_filename thumbo
20
+ "#{self.object_id}_#{thumbo.title}.#{thumbo.fileext}"
21
+ end
22
+
23
+ def thumbo_uri thumbo
24
+ first, last = thumbo.filename.split('_')
25
+ "http://img.godfat.org/photos/#{first}_zzz_#{last}"
26
+ end
27
+
28
+ def thumbo_default_fileext
29
+ 'png'
30
+ end
31
+
32
+ end
33
+
34
+ class ThumboDefault
35
+ include Thumbo
36
+
37
+ def self.thumbo_common
38
+ {:common => 200}
39
+ end
40
+
41
+ def self.thumbo_square
42
+ {:square => 50}
43
+ end
44
+
45
+ def thumbo_default_fileext
46
+ 'png'
47
+ end
48
+ end
49
+
50
+ class StorageTest < TestCase
51
+ def test_uri
52
+ p = Photo.new
53
+ t = p.thumbos[:original]
54
+ t.from_blob(File.open('test/ruby.png').read)
55
+
56
+ assert_equal( "http://img.godfat.org/photos/#{p.object_id}_zzz_original.png",
57
+ p.thumbos[:original].uri )
58
+ end
59
+
60
+ def test_default
61
+ p = ThumboDefault.new
62
+ t = p.thumbos[:original]
63
+ t.from_blob(File.open('test/ruby.png').read)
64
+ t.write
65
+
66
+ assert_equal( "public/images/thumbo/#{Digest::MD5.hexdigest(t.filename)[0,1]}" +
67
+ "/#{p.object_id}_original.png",
68
+ p.thumbos[:original].uri )
69
+ ensure
70
+ File.delete(t.uri)
71
+ end
72
+
73
+ def test_raises
74
+ assert_raises(Thumbo::FileNotFound) do
75
+ Photo.new.thumbos[:original].delete
76
+ end
77
+ end
78
+
79
+ def test_write_file
80
+ target = "public/images/thumbo/#{Digest::MD5.hexdigest('LICENSE')[0,1]}/LICENSE"
81
+ ThumboDefault.thumbo_storage.write_file('LICENSE', File.open('LICENSE'))
82
+ assert_equal(File.read('LICENSE'), File.read(target))
83
+ ensure
84
+ File.delete(target)
85
+ end
86
+ 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 < 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,37 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ Gem::Specification.new do |s|
4
+ s.name = %q{thumbo}
5
+ s.version = "0.6.0"
6
+
7
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
8
+ s.authors = ["Lin Jen-Shin (aka godfat 真常)"]
9
+ s.date = %q{2010-05-31}
10
+ s.description = %q{ create thumbnails via RMagick}
11
+ s.email = %q{godfat (XD) godfat.org}
12
+ s.extra_rdoc_files = ["CHANGES", "LICENSE", "NOTICE", "README.rdoc", "Rakefile", "TODO", "test/ruby.png", "thumbo.gemspec"]
13
+ s.files = ["CHANGES", "LICENSE", "NOTICE", "README.rdoc", "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", "test/helper.rb", "test/ruby.png", "test/test_storage.rb", "test/test_thumbo.rb", "thumbo.gemspec"]
14
+ s.homepage = %q{http://github.com/godfat/thumbo}
15
+ s.rdoc_options = ["--main", "README.rdoc"]
16
+ s.require_paths = ["lib"]
17
+ s.rubyforge_project = %q{thumbo}
18
+ s.rubygems_version = %q{1.3.7}
19
+ s.summary = %q{create thumbnails via RMagick}
20
+ s.test_files = ["test/test_storage.rb", "test/test_thumbo.rb"]
21
+
22
+ if s.respond_to? :specification_version then
23
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
24
+ s.specification_version = 3
25
+
26
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
27
+ s.add_runtime_dependency(%q<rmagick>, [">= 2.6.0"])
28
+ s.add_development_dependency(%q<bones>, [">= 3.4.3"])
29
+ else
30
+ s.add_dependency(%q<rmagick>, [">= 2.6.0"])
31
+ s.add_dependency(%q<bones>, [">= 3.4.3"])
32
+ end
33
+ else
34
+ s.add_dependency(%q<rmagick>, [">= 2.6.0"])
35
+ s.add_dependency(%q<bones>, [">= 3.4.3"])
36
+ end
37
+ end
metadata ADDED
@@ -0,0 +1,124 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: thumbo
3
+ version: !ruby/object:Gem::Version
4
+ hash: 7
5
+ prerelease: false
6
+ segments:
7
+ - 0
8
+ - 6
9
+ - 0
10
+ version: 0.6.0
11
+ platform: ruby
12
+ authors:
13
+ - "Lin Jen-Shin (aka godfat \xE7\x9C\x9F\xE5\xB8\xB8)"
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2010-06-07 00:00:00 +08:00
19
+ default_executable:
20
+ dependencies:
21
+ - !ruby/object:Gem::Dependency
22
+ name: rmagick
23
+ prerelease: false
24
+ requirement: &id001 !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ hash: 23
30
+ segments:
31
+ - 2
32
+ - 6
33
+ - 0
34
+ version: 2.6.0
35
+ type: :runtime
36
+ version_requirements: *id001
37
+ - !ruby/object:Gem::Dependency
38
+ name: bones
39
+ prerelease: false
40
+ requirement: &id002 !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ hash: 17
46
+ segments:
47
+ - 3
48
+ - 4
49
+ - 3
50
+ version: 3.4.3
51
+ type: :development
52
+ version_requirements: *id002
53
+ description: " create thumbnails via RMagick"
54
+ email: godfat (XD) godfat.org
55
+ executables: []
56
+
57
+ extensions: []
58
+
59
+ extra_rdoc_files:
60
+ - CHANGES
61
+ - LICENSE
62
+ - NOTICE
63
+ - README.rdoc
64
+ - Rakefile
65
+ - TODO
66
+ - test/ruby.png
67
+ - thumbo.gemspec
68
+ files:
69
+ - CHANGES
70
+ - LICENSE
71
+ - NOTICE
72
+ - README.rdoc
73
+ - Rakefile
74
+ - TODO
75
+ - lib/thumbo.rb
76
+ - lib/thumbo/exceptions/file_not_found.rb
77
+ - lib/thumbo/proxy.rb
78
+ - lib/thumbo/storages/abstract.rb
79
+ - lib/thumbo/storages/filesystem.rb
80
+ - lib/thumbo/storages/mogilefs.rb
81
+ - lib/thumbo/version.rb
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
+ licenses: []
90
+
91
+ post_install_message:
92
+ rdoc_options:
93
+ - --main
94
+ - README.rdoc
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ none: false
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ hash: 3
103
+ segments:
104
+ - 0
105
+ version: "0"
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ none: false
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ hash: 3
112
+ segments:
113
+ - 0
114
+ version: "0"
115
+ requirements: []
116
+
117
+ rubyforge_project: thumbo
118
+ rubygems_version: 1.3.7
119
+ signing_key:
120
+ specification_version: 3
121
+ summary: create thumbnails via RMagick
122
+ test_files:
123
+ - test/test_storage.rb
124
+ - test/test_thumbo.rb