meme_captain 0.0.8 → 0.0.9

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,70 +0,0 @@
1
- module MemeCaptain
2
-
3
- # Cache data on filesystem.
4
- class FilesystemCache
5
-
6
- def initialize(root_dir); @root_dir = root_dir; end
7
-
8
- # Get the data of a file in the cache.
9
- #
10
- # On cache miss, if block given, call block to get data from source and
11
- # cache it. If no block given return nil on cache miss.
12
- #
13
- # If suffixes are passed in, loop through them and search for base id +
14
- # suffix on filesystem. Return the data of the first found.
15
- def get_data(id, suffixes=[''])
16
- suffixes.each do |suffix|
17
- file_path = id_path(id, suffix)
18
- return open(file_path, 'rb') { |f| f.read } if File.exist?(file_path)
19
- end
20
-
21
- # not found in cache
22
- if block_given?
23
- data = yield
24
- put(id, data)
25
- data
26
- end
27
- end
28
-
29
- # Get the path of a file in the cache.
30
- #
31
- # On cache miss, if block given, call block to get data from source and
32
- # cache it. If no block given return nil on cache miss.
33
- #
34
- # If suffixes are passed in, loop through them and search for base id +
35
- # suffix on filesystem. Return the first found.
36
- def get_path(id, suffixes=[''])
37
- suffixes.each do |suffix|
38
- file_path = id_path(id, suffix)
39
- return file_path if File.exist?(file_path)
40
- end
41
-
42
- # not found in cache
43
- put(id, yield) if block_given?
44
- end
45
-
46
- # Put data in the cache and return its path.
47
- def put(id, data)
48
- mime_type = MemeCaptain.mime_type(data)
49
- unless mime_type
50
- raise 'Data loaded from source image url is not an image'
51
- end
52
- file_path = id_path(id, ".#{mime_type.extensions[0]}")
53
-
54
- open(file_path, 'w') do |f|
55
- f.flock(File::LOCK_EX)
56
- f.write(data)
57
- f.flock(File::LOCK_UN)
58
- end
59
- file_path
60
- end
61
-
62
- # Get the cache file path for an id with optional suffix added.
63
- def id_path(id, suffix=nil)
64
- File.join(root_dir, File.expand_path(id, '/')) + suffix.to_s
65
- end
66
-
67
- attr_reader :root_dir
68
- end
69
-
70
- end
@@ -1,20 +0,0 @@
1
- require 'mime/types'
2
-
3
- module MemeCaptain
4
-
5
- module_function
6
-
7
- # Determine mime type from blob of image data.
8
- def mime_type(img_data)
9
- mime_type_s = if img_data[0,2].unpack('H4')[0] == 'ffd8'
10
- 'image/jpeg'
11
- elsif img_data[0,8].unpack('H16')[0] == '89504e470d0a1a0a'
12
- 'image/png'
13
- elsif %w{474946383961 474946383761}.include?(img_data[0,6].unpack('H12')[0])
14
- 'image/gif'
15
- end
16
-
17
- MIME::Types[mime_type_s][0]
18
- end
19
-
20
- end